Fix input() returning None in Python

avatar

Borislav Hadzhiev

Last updated: Aug 24, 2022

banner

Photo from Unsplash

Fix input() returning None in Python #

The input() function most commonly returns None when passing it a call to the print() function. To get around this, make sure to pass a string to the input() function and not a call to the print() function.

main.py
# ⛔️ BAD (passing print() call to input()) user_input = input(print('Enter your preferred language: ')) print(user_input) # ------------------------------------------- # ✅ Good (passing a string to input()) user_input = input('Enter your preferred language: ') print(user_input)

The print() function prints a message and returns None.

main.py
result = print('hello') print(result) # 👉️ None

If you pass a call to the print() function to the input() function, it will return None.

Instead, make sure to pass a string to the input() function.

main.py
user_input = input('Enter your preferred language: ') print(user_input)

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 always returns a string, even if the user enters a number.

You can use the print() function to print a message before or after using the input() function, but not in the call to the input() function.

main.py
print('This runs before') user_input = input('Enter your preferred language: ') print(user_input) print('This runs after')

If you have to use variables in an input message, use a formatted string literal.

main.py
variable = 'language' user_input = input(f'Enter your preferred {variable}: ') print(user_input)

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

The most common sources of None values are:

  1. Having a function that doesn't return anything (returns None implicitly).
  2. Explicitly setting a variable to None.
  3. Assigning a variable to the result of calling a built-in function that doesn't return anything.
  4. Having a function that only returns a value if a certain condition is met.
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.