0

< 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?

2
  • The shown code isn't properly indented, please repair. Commented May 14, 2020 at 11:17
  • @chepner - you were on the case too quick (impressive) - I was still proofreading! Have amended. Commented May 14, 2020 at 11:21

2 Answers 2

2

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.")
Sign up to request clarification or add additional context in comments.

Comments

0

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. ")

Try it online!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.