Skip to content

Asking the user for input until they give a valid response Python | Code

  • by

Use the input function to take input from the user and if statement to match the user-given value. If the input value is matched, then use the break statement to exit the loop. While true will run until break not execute.

Use the while loop, and the break statement:

while True:
    # . . .
    if correct_answer:
        break

Example Asking the user for input until they give a valid answer Python

Simple example code

while True:
    ans = input("How many continents in the world?: ")
    if ans == "7":
        name = True
        print("Right")
        break
    else:
        print("\nThat is incorrect, please try again.\n") 

Output:

Asking the user for input until they give a valid response Python

Other examples

Keep repeating the question until the answer is considered to be acceptable by the program.

answers = ['alice', 'chris', 'bob']
answer = None
while answer not in answers:
    answer = input('Enter your answer: ')

print('Your answer was: {}'.format(answer))

Output:

Enter your answer: bob
Your answer was: bob

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can’t be parsed.

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

    if age < 0:
        print("Sorry, your response must not be negative.")
        continue
    else:
        break
if age >= 18:
    print("You are able to vote!")
else:
    print("You are not able to vote.")

Output:

Please enter your age: 18
You are able to vote!

Do comment if you have any doubts or suggestions on this Python code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading