Python 2.7.3 While Loop
I'm very new to python. I need to repeatedly loop, asking the user to select an option, then running the commands and repeating until the user chooses to exit. If the user selects
Solution 1:
The break
command will exit a loop for you - however, in terms of beginning control flow, it's not really recommended either. Note, however, the user can never input a new value and therefore you will be caught in an infinite loop.
Perhaps try this:
running = Truewhile 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
Solution 2:
This is how i would modify it to achieve the expected result.You where close but the if and else's shouldn't 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 you can use break to stop a loop at any time
Thanks Ben
Solution 3:
import sys
option = int(input("Please select one of the above options: "))
whilenot 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 option is not 0, 1, 2, or 3, the program keeps asking for input. If it is within that range, the loop ends and it prints the result. If the input is 0, the program ends using sys.exit()
.
Alternatively, you can use a dictionary to create a simpler, shorter program:
import sys
userOptions = {1: 'happy', 2: 'average', 3: 'sad'}
option = int(input("Please select one of the above options: "))
whilenot 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]
Post a Comment for "Python 2.7.3 While Loop"