Ask for Input Again if Input Is Wrong

Use input office to take input from the user and if statement to friction match the user given value. If the input value is matched, then use the interruption statement to get out the loop. While true volition run until pause not execute.

Use the while loop, and the pause statement:

          while True:     # . . .     if correct_answer:         break                  

Example Request the user for input until they requite a valid answer Python

Simple example lawmaking

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

Output:

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

Other examples

Keep repeating the question until the respond is considered to exist adequate past the plan.

          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

Utilize endeavour and except to discover when the user enters information that can't be parsed.

          while Truthful:     try:         age = int(input("Please enter your age: "))     except ValueError:         print("Sorry, I didn't understand that.")         go on      if age < 0:         print("Lamentable, your response must not be negative.")         keep     else:         break if age >= 18:     print("You lot are able to vote!") else:     print("You are not able to vote.")                  

Output:

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

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

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.x.ane

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

brownwoorst.blogspot.com

Source: https://tutorial.eyehunts.com/python/asking-the-user-for-input-until-they-give-a-valid-response-python-code/

0 Response to "Ask for Input Again if Input Is Wrong"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel