Prevent empty user input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 22, 2022

banner

Photo from Unsplash

Prevent empty user input in Python #

To prevent an empty user input:

  1. Use a while loop to iterate until the user enters a non-empty string.
  2. On each iteration, check if the user didn't enter an empty string.
  3. If the condition is met, break out of the while loop.
main.py
country = '' # ✅ prevents empty input while country == '': country = input('Where are you from: ') print(country) # --------------------------------------------- # ✅ prevents empty input (including whitespace characters) while country.strip() == '': country = input('Where are you from: ') print(country)

prevent empty user input

The first example keeps prompting the user when they enter an empty string.

The second example also considers whitespace characters as empty input.

We used a while loop to iterate until the country variable doesn't store an empty string.

main.py
country = '' while country == '': country = input('Where are you from: ')
If the user enters a value that contains at least 1 character, the condition is no longer met and we 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.

If you want to prevent the user from entering only spaces, use the str.strip() method.

main.py
country = '' while country.strip() == '': country = input('Where are you from: ')

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

main.py
print(repr(' '.strip())) # 👉️ '' print(repr(' hello '.strip())) # 👉️ 'hello'
The while loop keeps running until the user enters at least one, non-whitespace character.

Alternatively, you can use a while True loop.

main.py
while True: country = input('Where are you from: ') if country.strip() != '': print(country) break

On each iteration, we check if the user entered at least one character.

If the condition is met, we use the break statement to exit the loop.

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

Make sure to use the break statement because it is the only way to exit a while True loop.

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.