Validating user input string in Python

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

Validating user input string in Python #

To validate string user input values:

  1. Use a while loop to iterate until the provided value is valid.
  2. On each iteration, check if the provided string meets a condition.
  3. If the condition is met, break out of the loop.
main.py
options = ['a', 'b', 'c'] user_input = '' while user_input.lower() not in options: user_input = input('Enter a, b or c: ') print(user_input) # ---------------------------------------- # 👇️ check if user input string is at least 5 characters long 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)

validate string input

The first example checks if the provided user input string is one of the items in a list.

The while loop keeps prompting the user until the provided value is one of the options.

main.py
options = ['a', 'b', 'c'] user_input = '' while user_input.lower() not in options: user_input = input('Enter a, b or c: ') print(user_input)

If the supplied value is one of the options, the condition in the while loop is no longer met and we break out of the loop.

You can also use a while True loop with a break statement to validate string input values.

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)

validate string input while true

We used a while True loop to prompt the user for input.

If the user entered a value containing less than 5 characters, we use the continue statement to prompt the user again.

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

Otherwise, the else block runs where we print the value the user entered and break out of the loop.

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

When validating string input values, you might want to use the str.lower() or str.upper() methods to lowercase or uppercase the input value when comparing it to other strings.

main.py
print('HELLO'.lower()) # 👉️ 'hello' print('hello'.upper()) # 👉️ 'HELLO'
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.