How to Validate user input in Python

avatar
Borislav Hadzhiev

Last updated: Feb 20, 2023
6 min

banner

# Table of Contents

  1. Validating user input in Python
  2. Accept input until Enter is pressed in Python
  3. Fix input() returning None in Python

# 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 the 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.

# Prompting the user for input until validation passes

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 boolean AND operators if you need to check for multiple conditions.

# Validating user input based on multiple conditions (OR)

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.

# Validating user input based on multiple conditions (AND)

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.

# Accept input until Enter is pressed in Python

To accept input until the Enter key is pressed:

  1. Declare a variable that stores an empty list.
  2. Use a while loop to iterate an arbitrary number of times.
  3. Append each user input value to the list.
  4. Break out of the while loop when the user presses Enter.
main.py
# ✅ When taking strings as input my_list = [] user_input = '' while True: user_input = input('Enter a string: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break my_list.append(user_input) print(my_list) # --------------------------------------------- # ✅ When taking integers as input my_list = [] user_input = '' while True: user_input = input('Enter a number: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

repeat program until user input is correct

The examples repeat the program and keep taking user input until the user presses Enter without typing in a value.

This could be any other condition, e.g. if the user types done or if the list stores at least 3 input values.

The first example takes strings as input from the user.

main.py
my_list = [] user_input = '' while True: user_input = input('Enter a string: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break my_list.append(user_input) print(my_list)

We used a while loop to take user input while iterating an arbitrary number of times.

The only way to break out of a while True loop is to use a break statement or to raise an exception.

If the user presses Enter without typing in a value, we break out of the while loop.

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

Otherwise, we append the input value to the list.

The list.append() method adds an item to the end of the list.

Here is an example that keeps repeating the program until the user input is correct when taking integers.

main.py
my_list = [] user_input = '' while True: user_input = input('Enter a number: ') # 👇️ Take input until Enter is pressed without value if user_input == '': print('User pressed enter') break try: my_list.append(int(user_input)) except ValueError: print('Invalid number.') continue print(my_list)

repeat program until user input is correct integers

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 the input, converts it to a string and returns the result.

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

We used the int() class to convert each string to an integer.

The try/except statement is used to handle the ValueError that is raised if an invalid integer is passed to the int() class.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.