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]
source share