< I have the following code:
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "))
while choice not in ['1','2','3','4']:
choice = int(input("What would you like to choose [1,2,3,4]? "))
if not choice:
print: ("Please enter 1, 2, 3 or 4. ")
However, the output when running the module is:
What would you like to do [1,2,3,4]? 5 What would you like to do [1,2,3,4]?
I want this to loop until 1,2,3, or 4 is selected & produce the following output:
What would you like to do [1,2,3,4]? 7 Please enter 1, 2, 3 or 4.
What would you like to do [1,2,3,4]?
Where am I going wrong?
if not choice:
is equivalent to if choice == 0:
in this context, since you will only reach that statement after input
has returned and int
hasn't raised an exception.
Use the following idiom for a potentially infinite loop that doesn't duplicate the call to input
:
...
print("Option 4")
while True:
choice = int(input("..."))
if choice in [1, 2, 3, 4]:
break
print("Please enter 1, 2, 3, or 4.")
The colon after the line print: ("Please enter 1, 2, 3 or 4. ")
might be causing the string to not be printed. I don't know why that doesn't cause a syntax error though.
A pretty rudimentary solution.
print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = "0"
while choice not in ['1','2','3','4']:
choice = input("What would you like to choose [1,2,3,4]? ")
if choice not in ['1', '2', '3', '4']:
print ("Please enter 1, 2, 3 or 4. ")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.