How to Validate User Input in Python
Validating user input is crucial for creating robust and reliable Python applications. It helps prevent errors, ensures data integrity, and improves the user experience.
This guide explores various techniques for validating user input, covering numerical and string data, as well as multiple validation conditions.
Basic User Input Validation with Loops
The core concept of user input validation involves using a loop to repeatedly prompt the user until valid input is received. We can use while
loops combined with if
/else
statements and try
/except
blocks to achieve this.
1. Validating Integer Input
Here's how to validate integer user input to ensure it's within a specific range:
num = 0
while True:
try:
num = int(input("Enter an integer 1-10: "))
except ValueError:
print("Please enter a valid integer 1-10")
continue
if 1 <= num <= 10:
print(f'You entered: {num}')
break
else:
print('The integer must be in the range 1-10')
Explanation:
- The
while True
creates an infinite loop that will continue until explicitly broken. - The
try
block attempts to convert the user's input to an integer usingint()
. - If the user enters a non-numeric string, a
ValueError
is raised, which is caught by theexcept
block and prints a helpful error message. Thecontinue
statement restarts the loop, prompting the user again. - The
if 1 <= num <= 10
checks if the converted integer falls within the range of 1 to 10 (inclusive). If it does, a confirmation message is printed and thebreak
statement exits the loop. - If the integer is not within the specified range, the
else
statement runs, providing an error message, and the loop continues.
2. Validating String Input
Here's how to validate string input based on length:
password = ''
while True:
password = input('Enter your password: ')
if len(password) < 5:
print('Password too short')
continue
else:
print(f'You entered {password}')
break
print(password)
Explanation:
- The loop continues until the user enters a password of at least 5 characters.
- If the password length is less than 5, an error message is displayed, and the
continue
statement goes back to the beginning of the loop for the next iteration. - If the length is 5 or greater, a confirmation message is printed, and the
break
statement exits the loop.
Validating with Multiple Conditions (OR)
You can use the boolean or
operator to check if at least one of multiple conditions is met. Here's how to validate a password that is either too short or is a commonly used password:
password = ''
common_passwords = ['abcde', 'asdfg']
while True:
password = input('Enter your password: ')
if len(password) < 5 or password in common_passwords:
print('Pick a strong password')
continue
else:
print(f'You entered {password}')
break
print(password)
Explanation:
- If the password length is less than 5 or if the password is present in the list of
common_passwords
using thein
operator, theif
statement condition evaluates toTrue
, and an error message is printed. - The
continue
statement then skips the rest of the code block and continues with the next iteration of the while loop.
Validating with Multiple Conditions (AND)
You can use the boolean and
operator to check if all conditions are met. Here, we require both conditions be true, the password length has to be greater than 5 characters, and the password can not be a commonly used password.
password = ''
common_passwords = ['abcde', 'asdfg']
while True:
password = input('Enter your password: ')
if len(password) > 5 and password not in common_passwords:
print(f'You entered {password}')
break
else:
print('Pick a strong password')
continue
print(password)
Explanation:
- The
if
statement uses theand
keyword, so both conditions have to evaluate toTrue
for the code in theif
block to execute. The password has to have more than 5 characters, and has to not be incommon_passwords
using thenot in
operator.
Accepting Input Until Enter is Pressed
Sometimes, you need to take input until the user presses Enter
without providing any text. This is often used for collecting a variable number of inputs from the user.
1. String Input
Here's how to collect string input until an empty Enter
is pressed:
my_list = []
while True:
user_input = input('Enter a string: ')
if user_input == '':
print('User pressed enter')
break
my_list.append(user_input)
print(my_list)
Explanation:
- The
while True
loop keeps running until thebreak
statement is executed. - If the user types in any text and then presses enter, the string will be stored in the
user_input
variable, otherwise it will be an empty string. - If the
user_input
is an empty string (meaning that the user pressed enter without typing any text), thenbreak
is used to exit the loop, thus stopping the collection of input. - If a non-empty string was typed in, it is appended to the
my_list
list usingappend()
.
2. Integer Input
Here's how to collect integer input until an empty Enter
is pressed, handling ValueError
exceptions:
my_list = []
while True:
user_input = input('Enter a number: ')
if user_input == '':
print('User pressed enter')
break
try:
my_list.append(int(user_input))
except ValueError:
print('Invalid number.')
continue
print(my_list)
Explanation:
- This code is similar to the previous example, but it tries to convert each input to an integer.
- The
try/except
block handles theValueError
exception, if the user types in a non-numeric character.