Skip to content

Python while loop input validation | Example code

  • by

Data validation is important when the user input it. It makes sure it is valid before it is used in a computation. You can do Input Validation with While Loops in Python.

Example while loop input validation in Python

Simple example code While loop with List calculates BMI in Python.

choice = "Y"
valid = ("Y", "y", "n", "N")
yes_list = ("Y", "y", "yes", "Yes", "YES")

while choice in yes_list:
    weight = float(input("How much do you weight? "))
    height = float(input("How tall are you in inches? "))

    bmi = 703 * (weight / (height * height))
    print("Your BMI is: %.2f" % bmi)

    choice = input("Another BMI calculation (Y/N)? ")
    while choice not in valid:
        choice = input("Invalid choice.  Enter a Y or N? ")

Output:

Python while loop input validation

Menu input validation with string user input

def menu():
    print("MAIN MENU")
    print("-----------------")
    print("1. Print pay check")
    print("2. Change benefits")
    print("3. Exit")
    choice = input("Choose menu option (1-3): ")
    while choice not in ['1', '2', '3']:
        choice = input("Invalid choice.  Choose menu option (1-3): ")
    return int(choice)


menu_chosen = True
choice = menu()
print("You chose menu option", choice)

Output:

MAIN MENU

  1. Print pay check
  2. Change benefits
  3. Exit
    Choose menu option (1-3): 1
    You chose menu option 1

Do comment if you have any doubts or suggestions about this Python input validation 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

Your email address will not be published. Required fields are marked *