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


	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): d
  Invalid choice. Choose menu option (1-3): 3
  You chose menu option 3


Example: While True loop with function in Python


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

	while True:
		rad = int(input("Enter a radius: "))
		calcAreaCircle(rad)

		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:

  Enter a radius: 2
  Area of circle is 12.57
  Perform another calculation (y/n? pp
  Invalid choice. Please enter y or n: y
  Enter a radius: 3
  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"]

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

	while True:
		rad = int(input("Enter a radius: "))
		calcAreaCircle(rad)

		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:

  Enter a radius: 2
  Area of circle is 12.57
  Perform another calculation (y/n? rr
  Invalid choice. Please enter y or n: 2
  Invalid choice. Please enter y or n: y
  Enter a radius: 3
  Area of circle is 28.27
  Perform another calculation (y/n? n