Python: How to keep repeating a program until a specific input is received?

I have a function that evaluates input, and I need to continue to request their input and evaluate it until they enter an empty string. How can I customize this?

while input != '': evaluate input 

I was thinking about using something like this, but it didn’t quite work. Any help?

+7
python loops for-loop while-loop
source share
4 answers

There are two ways to do this. At first it is something like this:

 while True: # Loop continuously inp = raw_input() # Get the input if inp == "": # If it is a blank line... break # ...break the loop 

The second example looks like this:

 inp = raw_input() # Get the input while inp != "": # Loop until it is a blank line inp = raw_input() # Get the input again 

Note that if you are on Python 3.x, you need to replace raw_input with input .

+17
source share

you probably want to use a separate value that keeps track of if the input is valid:

 good_input = None while not good_input: user_input = raw_input("enter the right letter : ") if user_input in list_of_good_values: good_input = user_input 
+1
source share

This is a small program that will continue to request input until the required input is entered.

 required_number = 18 while True: number = input("Enter the number\n") if number == required_number: print "GOT IT" else: print ("Wrong number try again") 
0
source share

A simpler way:

 #required_number = 18 required_number=input("Insert a number: ") while required_number != 18 print("Oops! Something is wrong") required_number=input("Try again: ") if required_number == '18' print("That right!") #continue the code 
0
source share

All Articles