Setting default values on empty user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 24, 2022

banner

Photo from Unsplash

Setting default values on empty user Input in Python #

Use the or boolean operator to set a default value on empty user input, e.g. user_input = input('Enter your preferred language: ') or 'default'. The boolean or operator will return the default value if the input is empty.

main.py
default = 'English' user_input = input('Enter your preferred language: ') or default print(user_input) # ------------------------------------------- default = 100 user_input = int(input('Enter an integer: ') or default) print(user_input)

set default value on empty user input

We used the boolean or operator to set a default value on empty user input.

The expression x or y returns the value to the left if it's truthy, otherwise the value to the right is returned.

main.py
print('' or 'default value') # 👉️ default value print('hello' or 'default value') # 👉️ hello
The boolean or operator will return the value to the right if the value to the left is falsy.

The input() function returns an empty string if the user didn't enter a value.

Empty strings are falsy, so if the user presses Enter without typing in a value, the default value is returned.

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.

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

Here is an example that sets a default value on empty user input when a number is expected.

main.py
default = '100' user_input = int(input('Enter an integer: ') or default) print(user_input)

input with default numeric

We used the int() class to convert the input string to a number.

The or operator returns the default value if the user didn't type in anything.

Alternatively, you can use an if statement.

To set a default value on empty user input:

  1. Use the input() function to take input from the user.
  2. Use an if statement to check if the input value is an empty string.
  3. If the input value is an empty string, set it to the default value.
main.py
default = 'English' user_input = input('Enter your preferred language: ') if user_input == '': user_input = default print(user_input)

We used an if statement to check if the input value is an empty string.

If it is, we reassign the user_input variable to a default value.

This approach is a bit more verbose, however, it might be easier to read if you're not familiar with the boolean or operator.

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.