How to catch specific words in Python Input - python

I am creating a python program to deal with Clock and Time. The question arises where user puts input to set a timer for 90 seconds, or any 'n' seconds. Here is the code-
inp=input("How can I help you ? : ")
if ("timer" in inp):
print("setting up...")
a=int(input("Enter no. of seconds : ")
import time
while (a != 0):
print(a)
a-=1
time.sleep(1)
Now I want such an interface to directly catch the specific number of seconds directly from inp variable.
Is it possible?

If you know for sure that the user will input timer x (x is the number of seconds), you can just do the following:
import time
inp=input("How can I help you ? : ")
if ("timer" in inp):
time.sleep(int(inp))
But most of the time you will probably want to do some user input validation.

A quick and dirty solution would be:
inp = input("How can I help you ? : ")
# assuming input is "timer 90"
inp = inp.split(" ")
if inp[0] == "timer":
a = int(inp[1])
import time
while (a != 0):
print(a)
a-=1
time.sleep(1)

Yes it is possible. But you need to specify the protocol first. Like you can input timer and the value in same user input using some delimiter or anything, but that needs to be decided first.
Here is an example where I input timer and value both using , as delimiter.
import time
inp=input("How can I help you ? : ")
# I will input --> timer,10
if ("timer" in inp):
secs = int(inp.split(",")[1].strip())
print("Got timer for sleep is : {0}".format(secs))
while (secs != 0):
print(secs)
secs-=1
time.sleep(1)

Related

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

Closing a program when a condition is met

I am just starting out and can't figure this one out.
I am writing a program to do some simple calculations for me at school.
Different calculations will be accessible through input of simple numbers from 1 to X. Every number will call a function just for that calculation.
My problem is this:
I want that if the user enters an empty string when prompted for a number, the program will ask the user to re enter a number for a certain amount of times before closing. Here's my code:
def pick_procedure():
procedure = raw_input("> ")
if not procedure:
counter = 0
print "Enter a value. "
while counter <4:
counter = counter + 1
main()
if counter == 4:
break
def main():
print "\nStudy helper 1.0.\n"
print """Procedure list:
1.Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
pick_procedure()
main()
No matter how many times an empty string is entered, the program does not close.
How to do it correctly and cleaner?
As you say, you need to reorganise your code:
def pick_procedure(valid_choices):
print "Enter a value. "
for _ in range(4): # prompt for a choice up to 4 times
choice = raw_input("> ")
if choice in valid_choices:
return choice
return None # A valid choice was not entered
def main():
print "\nStudy helper 1.0.\n"
choice = 1
while choice:
print """Procedure list:
1. Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
choice = pick_procedure(["1", "2"])
if choice:
print "Doing choice", choice
main()
The following approach makes use of a while choice loop to keep prompting if a valid choice is entered. If no choice is entered 4 times, the pick_procedure() function returns None causing the while loop to exit cleanly. If a valid choice is entered, it returns that choice.
I also pass the list of valid responses to the function, that way the function can be used for other questions simply by passing a different list of valid responses.
You created a vicious circle.
First time that procedure is false, pick_procedure calls main and then main calls again pick_procedure. It continues recursively.
If you just want to finish the program when an event is fired, you can use sys.exit(0) and your problems are solved.

time pass algorithm in python

import time
import random
info = """welcome to contest!..
pls answer question as quick as possible you can
pls enter small letter...\n"""
print(info)
questions = {"2 * 2 ?":"4",
"what is the capital city of turkey?":"ankara",
"what is the king of jungle?":"lion",
"what is the meaning of book in turkish language?":"kitap",
"who is the foundation of turkish government":"atatürk",
"what is the most popular drink in turkey?":"raki",
"pls tell us a hero as comic":"temel"}
correct = 0
wrong = 0
blank = 0
current_time = time.time() #system time
allowed_time = 25 #total time to reply the question
for i in random.sample(list(questions), 5):
question = questions[i]
if time.time() < current_time+allowed_time:
answer = input("1. soru --> {} : ".format(i))
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
print()
print("right answer :", correct)
print("wrong answer :", wrong)
print("blank answer :", blank)
Please see my survey code above. It's selecting random 5 question in total time 25 seconds. But, I'd like to make it time option for every single question.
For example, questions must be replied with in ten seconds otherwise change question automatically.
Could you help on how to do that?
here's the steps to proceed(algorithm):
Add a timer to each question.
Run a counter or a timer inside the for loop, then, for every iteration passed, store the time in a variable x, check if x is less than 10.
Check whether it is answered within 10 seconds.
Iterate to the Next question, this i+1.
If NOT, jump to the next question.
The input() function - by its definition - waits for the input infinitely. Probably there is no cross-platform solution for it.
For *nix operating systems you may do this:
Create another thread with the timer which will interrupt the main thread after some time limit.
You may define a function for your input which will do it:
import thread # _thread for Python 3.x
import threading
def timed_input(prompt, timeout=25.):
timer = threading.Timer(timeout, thread.interrupt_main)
answer = ""
try:
timer.start()
answer = input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return answer
and then use it instead of the standard input() function in your code (and of course without your original attempts with the time module).
Probably the most simple and the most elegant (from the programmer's point of view) is simply to keep infinitely time for an answer but then reject it if it was answered after the given time limit:
start_time = time.time()
answer = input("1. soru --> {} : ". format(i))
if time.time() - start_time > allowed_time:
# code for rejecting the answer
So instead of your for loop use this (a tested one, and with an improvement):
for j, i in enumerate( random.sample(list(questions), 5) ): # Slight change
question = questions[i]
start_time = time.time()
answer = input("{}. soru --> {} : ". format(j + 1, i)) # Sligth change
if time.time() - start_time > allowed_time:
print(" Time-out: You didn't answer quickly enough.")
answer = ""
if answer == question:
correct += 1
elif answer == "":
blank += 1
else:
wrong += 1
Not that I slightly changed your for statement and the answer = ... for the sake of printing correct ordinal numbers of questions (yours were always 1.)

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Using User Input to control parameters in a Random number Generator

I am attempting to write a program that generates random numbers, asks how big you want it, between 1-4 for example, then I want it to ask how many numbers you want and finally ask you if you want to run it again. I am attempting to grasp the concepts of recursion and type casting, just trying to learn the concepts of Object Orientated Design with Python. I tried to glean from what I have read so far on the Learn Python Hard Way site.
from random import randint
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
# Here I am attempting to define the variables I need to convert keyboard input to int
size = raw_input()
intsize = # unsure of how to define this variable
intsize = int(size)
print "How many Digits?",
size = raw_input()
print "How many Times?".
times = raw_input()
# I want to construct a method here that sends my size input to random_with_N_digits(n)
# I need a method that runs the random_with_N_digits according to the input.
# while True:
reply = input('Enter text:')
if reply == 'stop':
break
if reply = times # not sure what to put here
print( def random_with_N_digits)
else:
# I want to tell the my method to run as many as much as 'times' is equal to
print "Again?"
answerMe = raw_input()
# here I want to have a if answerMe = Enter run the method again
print random_with_N_digits()
try this code
from random import randint
def random_with_N_digits(n):
s = int(raw_input("starting from.. "))
e = int(raw_input("upto... "))
l = ""
for i in range(0,n):
l= l +str( randint(s,e))
print int(l)
again = raw_input("print again?")
if again == "yes":
how_many =int(raw_input("how many digits?"))
random_with_N_digits(how_many)
how_many =int(raw_input("how many digits?"))
random_with_N_digits(how_many)

Categories