Using variables inside an Input statement in Python

avatar

Borislav Hadzhiev

Last updated: Aug 23, 2022

banner

Photo from Unsplash

Using variables inside an Input statement in Python #

Use a formatted string literal to use variables inside an input statement, e.g. user_input = input(f'Enter a number between {num1} and {num2}: '). Formatted string literals let us include variables inside of strings by prefixing the string with f.

main.py
# ✅ Using variables inside an input statement (f-string) num1 = 1 num2 = 100 user_input = input(f'Enter a number between {num1} and {num2}: ') print(user_input) # ------------------------------------------------- # ✅ Using variables inside an input statement (str.format()) user_input = input('Enter a number between {} and {}: '.format(num1, num2)) print(user_input)

input state with variables

The first example uses a formatted string literal to include variables inside an input prompt.

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 input function takes an optional prompt argument and writes it to standard output without a trailing newline.

The prompt we pass to the input function is a string, so we can prefix it with f to include expressions.

main.py
num1 = 1 num2 = 100 user_input = input(f'Enter a number between {num1} and {num2}: ') print(user_input) # 👉️ '50'
Note that the input function is guaranteed to return a string even if the user enters a number.

If you need to take numeric input, use the int() or float() classes to convert the string to a number.

main.py
num1 = 1 num2 = 100 try: user_input = int(input(f'Enter an integer between {num1} and {num2}: ')) except ValueError: print('Invalid integer') print(user_input)

An alternative to using a formatted string literal is to use the str.format() method.

main.py
num1 = 1 num2 = 100 user_input = input('Enter a number between {} and {}: '.format(num1, num2)) print(user_input)

The str.format method performs string formatting operations.

The string the method is called on can contain replacement fields specified using curly braces {}.

Make sure to provide exactly as many arguments to the format() method as you have replacement fields in the string.

You should use formatted string literals most of the time. The syntax is easier to read because the variables are placed directly in the string and not in a separate function call.

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.