Python 2.7.3 while loop

I am very new to python. I need to repeat the loop, asking the user to select a parameter, then run the commands and repeat until the user decides to exit. If the user selects any other option, the program should continue to ask them to select a value until they select the correct one. So far, my program is not going so well. I would like, if, elif conditions, if possible. Can anybody help? Thank you very much!

print """ How do you feel today? 1 = happy 2 = average 3 = sad 0 = exit program """ option = input("Please select one of the above options: ") while option > 0 or option <=3: if option > 3: print "Please try again" elif option == 1: print "happy" elif option == 2: print "average" elif option == 3: print "sad" else: print "done" 
+4
source share
3 answers

The break command will exit the loop for you - however, from the point of view of the initial control flow, this is also not recommended. However, note that the user can never enter a new value, and therefore you end up in an infinite loop.

Perhaps try the following:

 running = True while running: option = input("Please select one of the above options: ") if option > 3: print "Please try again" elif option == 1: print "happy" elif option == 2: print "average" elif option == 3: print "sad" else: print "done" running = False 
+4
source

Here is how I could change it to achieve the expected result. You where close, but if and else should not be inside the loop :).

 print """ How do you feel today? 1 = happy 2 = average 3 = sad 0 = exit program """ option = input("Please select one of the above options: ") while option >3: print "Please try again" option = input("Please select one of the above options: ") if option == 1: print "happy" elif option == 2: print "average" elif option == 3: print "sad" else: print "done" 

Note that you can use break to stop the loop at any time.

Thanks Ben

+2
source
 import sys option = int(input("Please select one of the above options: ")) while not option in (0, 1, 2, 3): option = int(input("Please select one of the above options: ") if option == 0: sys.exit() else: print "Please try again" if option == 1: print "happy" elif option == 2: print "average" elif option == 3: print "sad" 

The logic is that if the parameter is not 0, 1, 2 or 3, the program continues to request input. If it is in this range, the loop ends and it prints the result. If the input is 0, the program ends using sys.exit() .

Alternatively, you can use the dictionary to create a simpler and shorter program:

 import sys userOptions = {1: 'happy', 2: 'average', 3: 'sad'} option = int(input("Please select one of the above options: ")) while not option in (0, 1, 2, 3): option = int(input("Please select one of the above options: ") if option == 0: sys.exit() else: print "Please try again" print userOptions[option] 
+1
source

All Articles