Validating user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

Validating user input in Python #

To validate user input:

  1. Use a while loop to iterate until the provided input value is valid.
  2. Check if the input value is valid on each iteration.
  3. If the value is valid, break out of the while loop.
main.py
# ✅ Validating integer user input 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 num >= 1 and num <= 10: print(f'You entered: {num}') break else: print('The integer must be in the range 1-10') # ---------------------------------------------- # ✅ Validating string user input 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)

input validation numbers

The first example validates numeric user input in a while loop.

If the try block completes successfully, then the user entered an integer.

main.py
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 num >= 1 and num <= 10: print(f'You entered: {num}') break else: print('The integer must be in the range 1-10')

The if statement checks if the integer is in the range 1-10 and if the condition is met, we break out of the while loop.

The break statement breaks out of the innermost enclosing for or while loop.

If the integer is not in the specified range, the else block runs and prints a message.

If the user didn't enter an integer, the except block runs, where we use the continue statement to prompt the user again.

The continue statement continues with the next iteration of the loop.

When validating user input in a while loop, we use the continue statement when the input is invalid, e.g. in an except block or an if statement.

If the input is valid, we use the break statement to exit out of the while loop.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The function then reads the line from input, converts it to a string and returns the result.

Note that the input() function is always guaranteed to return a string, even if the user enters a number.

You can use the same approach when validating user input strings.

Here is an example that prompts the user for input until they enter a value that is at least 5 characters long.

main.py
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)

input validation strings

The while loop keeps iterating until the user enters a value that has a length of at least 5.

If the value is too short, we use the continue statement to continue to the next iteration.

If the value is at least 5 characters long, we use the break statement as the input is valid.

You can use the boolean or and and operators if you need to check for multiple conditions.

Here is an example that checks if the input value is at least 5 characters long and not in a list of values.

main.py
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)

input validation or operator

The if statement checks if the password is less than 5 characters or is in the commonly used passwords list.

We used the boolean or operator, so the if block runs if either of the two conditions is met.

If the password is less than 5 characters or is contained in the commonly used passwords list, we continue to the next iteration and prompt the user again.

Use the and boolean operator if you need to check if multiple conditions are met when validating the input.

main.py
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)

We used the and boolean operator, so for the if block to run both conditions have to be met.

The password has to be longer than 5 characters and it has to not be in the commonly used passwords list.

If the conditions are met, we use the break statement to exit out of the while True loop.

If the conditions aren't met, we use the continue statement to continue to the next iteration.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.