Python: Input Validation


Python: Input Validation

In this program, user input is requested as a string (and stored in the variable named 'a'). The string user input prevents the program from crashing if a float or string is entered. A try statement then tests whether it is integer. If the user input (a) is a integer, the else clause runs, the user input is converted (cast) into an integer and then printed out to the screen. If the user input was not an integer, the except clause runs, an error message is outputted, and the program ends. In the next example we will add a loop so the user input is continued to be asked for until entered correctly.


Example: Simple Try ... Except to validate User input integer input


	a=input("Amount: ")
	try:
		int(a)
	except ValueError:
		print(a, "is not an integer number")
	else:
	    int(a)
		print (a, "is an integer number")
	

Output:

  Amount: 2
2 is an integer number


Example: User input integer input validation in a loop


	while True:
		a=input("Amount: ")
		try:
			int(a)
		except ValueError:
			print(a, "is not an integer number.  Please re-enter.")
		else:
			int(a)
			print (a, "is an integer number")
			break
	

Output:

  Amount: d
  d is not an integer number. Please re-enter.
  Amount: 2.2
  2.2 is not an integer number. Please re-enter.
  Amount: 2
  2 is an integer number


Example: User input integer input validation and a loop

The example below also adds the feature of calling a user-defined function and passing in a prompt. In the function, the user is asked for integer input. If this fails (i.e. a data type error), the except is executed, an error message displayed, and the loop runs the try user input again. If the user input is an integer, the else executed, the user input is converted (cast) to an integer data type, and returned to the main part of the program.


	def inputNum(prompt):
	   while True:
		  try:
			 userInput = int(input(prompt))
		  except ValueError:
			 print("Not an integer.  Please enter an integer.")
		  else:
			 return int(userInput)
			 break

	age = inputNum("Enter your age: ")
	print("Your age is: ", age)
	

Output:

  Enter your age: dog
  Not an integer. Please enter an integer.
  Enter your age: 24.44
  Not an integer. Please enter an integer.
  Enter your age: 25
  Your age is: 25


Example: User input validation of number (float or integer) in loop


	while True:
    a=input("Amount (float or integer): ")
    try:
        float(a)
    except ValueError:
        print(a, "is not an float or integer number.  Please re-enter.")
    else:
        float(a)
        print (a, "is a number")
        break
	

Output:

  Amount (float or integer): ttrrffgg
  ttrrffgg is not an float or integer number. Please re-enter.
  Amount (float or integer): 2.2
  2.2 is a number


Example: Numeric input validation with loop


	while True:
		try:
			x = int(input("Please enter a number: "))
			break
		except ValueError:
			print("Oops! That was no valid number. Try again...")
	

Output:

  Please enter a number: dddd
  Oops! That was no valid number. Try again...
  Please enter a number: 2.2
  Oops! That was no valid number. Try again...
  Please enter a number: 2


Example: Numeric and range input validation with function and loop


	def validHeight(cm):
		try:
			cm = float(cm)
			return 100 <= cm <= 250
		except ValueError:
			return False

	checkHeight = validHeight(input("Please enter height: "))
	while not checkHeight:
		print("Invalid height")
		checkHeight = validHeight(input("Please enter height: "))

	print("Valid height")
	

Output:

  Please enter height: 1
  Invalid height
  Please enter height: dd
  Invalid height
  Please enter height: 120
  Valid height


Example: Integer and range input validation in loop


	while True:
		try:
			num = int(input("Enter a number between 1 and 100: "))
			if num in range(1,100):
				break
			else:
				print("Invalid number. Try again.")
		except:
			print("That is not a number. Try again.")
	

Output:

  Enter a number between 1 and 100: dog
  That is not a number. Try again.
  Enter a number between 1 and 100: 33333
  Invalid number. Try again.
  Enter a number between 1 and 100: 2


Example: Integer and range input validation with function and loop


	def inputNum(prompt):
		while True:
			try:
				userInput = int(input(prompt))
			except ValueError:
				print("Not an integer! Try again.")
				continue
			else:
				return userInput
				break

	age = inputNum("How old are you? ")
	if (age >= 18):
		print("You are old enough to vote.")
	else:
		print("You will be able to vote in " + str(18-age) + " year(s).")
	

Output:

  How old are you? dog
  Not an integer! Try again.
  How old are you? 2.2
  Not an integer! Try again.
  How old are you? 19
  You are old enough to vote.


Example: User input check for null (empty)


	while True:
		try:
			fname= input("Please enter your first name: ")
			if not fname:
				raise ValueError('You did not enter anything. Please re-enter.')
		except ValueError as error:
			print(error)
		else:
			print("Thank you for entering your name", fname)
			break
	

Output:

  Please enter your first name:
  You did not enter anything. Please re-enter.
  Please enter your first name: John
Thank you for entering your name John


Example: Integer and range input validation in function and loop


	def validateCredits1(prompt):
		while True:
			try:
				type = int(input(prompt))
			except ValueError:
				print("Value must be between 0 and 25. Please re-enter.")
				continue
			else:
				while type < 0 or type > 25:
					print("Value must be between 0 and 25. Please re-enter.")
					type = validateCredits1("How many 100-200 level credits do you plan to "
											"register for (0-25)?:")
				return type

	credits1 = validateCredits1("How many 100-200 level credits do you plan to register "
								"for (0-25)?")
	

Output:

  How many 100-200 level credits do you plan to register for (0-25)?dog
  Value must be between 0 and 25. Please re-enter.
  How many 100-200 level credits do you plan to register for (0-25)?33
  Value must be between 0 and 25. Please re-enter.
  How many 100-200 level credits do you plan to register for (0-25)?:2


Example: Positive integer input validation


	while True:
		try:
			a = int(input("Enter a positive integer: "))
			if a <= 0:
				raise ValueError("That is not a positive number. Please re-enter.")
		except ValueError as error:
			print("Non-integer input. Please enter positive integer.")
		else:
			print("Thank you for entering a positive number.")
			break
	

Output:

  Enter a positive integer: CAT
  Non-integer input. Please enter positive integer.
  Enter a positive integer: -2
  Non-integer input. Please enter positive integer.
  Enter a positive integer: 2
  Thank you for entering a positive number.