# Python: Input Validation with While Loops

#### Example: While loop with List 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("Would you like to make another BMI calculation (Y/N)? ")
while choice not in valid:
choice = input("Invalid choice.  Enter a Y or N? ")
``````

#### Example: Menu input validation with string user input

``````
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)

``````

Output:

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

#### Example: While True loop with function in Python

``````
area = 3.14159 * (rad ** 2)
print("Area of circle is %.2f" % area)

while True:

againYN = input("Perform another calculation (y/n? ")
while againYN not in ["y","n","Y","N","Yes","No"]:
againYN = input("Invalid choice.  Please enter y or n: ")
if againYN in ["n","N","No"]:
break
``````

Output:

Area of circle is 12.57
Perform another calculation (y/n? pp
Invalid choice. Please enter y or n: y
Area of circle is 28.27
Perform another calculation (y/n? n

#### Example: While True loop with function and lists in Python

``````
all_list = ["y","n","Y","N","Yes","No"]
no_list = ["n","N","No"]

area = 3.14159 * (rad ** 2)
print("Area of circle is %.2f" % area)

while True:

againYN = input("Perform another calculation (y/n? ")
while againYN not in all_list:
againYN = input("Invalid choice.  Please enter y or n: ")
if againYN in no_list:
break
``````

Output: