How to Ask for User Input to Run Program Again

Apply input function to have 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 truthful will run until break non 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 reply Python

Unproblematic example code

          while True:     ans = input("How many continents in the earth?: ")     if ans == "7":         proper name = True         print("Correct")         suspension     else:         print("\nThat is incorrect, delight endeavor again.\n")                  

Output:

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

Other examples

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

          answers = ['alice', 'chris', 'bob'] reply = None while answer not in answers:     answer = input('Enter your answer: ')  print('Your reply was: {}'.format(answer))                  

Output:

Enter your answer: bob
Your answer was: bob

When Your Input Might Enhance an Exception

Apply effort and except to observe when the user enters data that can't be parsed.

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

Output:

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

Practise comment if you accept any doubts or suggestions on this Python lawmaking.

Note: IDE: PyCharm 2021.3 (Community Edition)

Windows 10

Python 3.10.1

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

maciaseaus1963.blogspot.com

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

0 Response to "How to Ask for User Input to Run Program Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel