Python provides interactive capabilities through various tools, one of which is the input() function. Its primary purpose is to receive user input. This function makes Python programs meaningful because without user interaction, applications would have limited utility.
This function operates as follows:
user_name = input('Enter your name: ')
user_age = int(input('How old are you? '))
First, the user is asked to enter their name, then their age. Both inputs are captured using a special operator that stores the entered values in the variables user_name
and user_age
. These values can then be used in the program.
For example, we can create an age-based access condition for a website (by converting the age input to an integer using int()
) and display a welcome message using the entered name:
if user_age < 18:
print('Sorry, access is restricted to adults only')
else:
print('Welcome to the site,', user_name, '!')
So, what happens when int()
receives an empty value? If the user presses Enter without entering anything, let's see what happens by extending the program:
user_name = input('Enter your name: ')
user_age = int(input('How old are you? '))
if user_age < 18:
print('Sorry, access is restricted to adults only')
else:
print('Welcome to the site,', user_name, '!')
input('Press Enter to go to the menu')
print('Welcome to the menu')
Pressing Enter moves the program to the next line of code. If there is no next line, the program exits. The last line can be written as:
input('Press Enter to exit')
If there are no more lines in the program, it will exit. Here is the complete version of the program:
user_name = input('Enter your name: ')
user_age = int(input('How old are you? '))
if user_age < 18:
print('Sorry, access is restricted to adults only')
else:
print('Welcome to the site,', user_name, '!')
input('Press Enter to go to the menu')
print('Welcome to the menu')
input('Press Enter to exit')
input('Press Enter to exit')
If the user enters an acceptable age, they will see the message inside the else
block. Otherwise, they will see only the if
block message and the final exit prompt. The input()
function is used four times in this program, and in the last two cases, it does not store any values but serves to move to the next part of the code or exit the program.
The above example is a complete program, but you can also execute it line by line in the Python interpreter. However, in this case, you must enter data immediately to continue:
>>> user_name = input('Enter your name: ')
Enter your name: Jamie
>>> user_age = int(input('How old are you? '))
How old are you? 18
The code will still execute, and values will be stored in variables. This method allows testing specific code blocks. However, keep in mind that values are retained only until you exit the interactive mode. It is recommended to save your code in a .py
file.
Sometimes, we need to convert user input into a specific data type, such as an integer, a floating-point number, or a list.
int()
)We've already seen this in a previous example:
user_age = int(input('How old are you? '))
The int()
function converts input into an integer, allowing Python to process it as a numeric type. By default, numbers entered by users are treated as strings, so Python requires explicit conversion. A more detailed approach would be:
user_age = input('How old are you? ')
user_age = int(user_age)
The first method is shorter and more convenient, but the second method is useful for understanding function behavior.
float()
)To convert user input into a floating-point number, use float()
:
height = float(input('Enter your height (e.g., 1.72): '))
weight = float(input('Enter your weight (e.g., 80.3): '))
Or using a more detailed approach:
height = input('Enter your height (e.g., 1.72): ')
height = float(height)
weight = input('Enter your weight (e.g., 80.3): ')
weight = float(weight)
Now, the program can perform calculations with floating-point numbers.
split()
)The split()
method converts input text into a list of words:
animals = input('Enter your favorite animals separated by spaces: ').split()
print('Here they are as a list:', animals)
Example output:
Enter your favorite animals separated by spaces: cat dog rabbit fox bear
Here they are as a list: ['cat', 'dog', 'rabbit', 'fox', 'bear']
Users often make mistakes while entering data or may intentionally enter incorrect characters. In such cases, incorrect input can cause the program to crash:
>>> height = float(input('Enter your height (e.g., 1.72): '))
Enter your height (e.g., 1.72): 1m72
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
height = float(input('Enter your height (e.g., 1.72): '))
ValueError: could not convert string to float: '1m72'
The error message indicates that Python cannot convert the string into a float. To prevent such crashes, we use the try-except
block:
try:
height = float(input('Enter your height (e.g., 1.72): '))
except ValueError:
height = float(input('Please enter your height in the correct format: '))
We can also modify our initial age-input program to be more robust:
try:
user_age = int(input('How old are you? '))
except ValueError:
user_age = int(input('Please enter a number: '))
However, the program will still crash if the user enters incorrect data again. To make it more resilient, we can use a while
loop:
while True:
try:
height = float(input('Enter your height (e.g., 1.72): '))
break
except ValueError:
print('Let’s try again.')
continue
print('Thank you!')
Here, we use a while
loop with break
and continue
. The program works as follows:
print('Thank you!')
.ValueError
) and displays the message "Let’s try again." continue
statement prevents the program from crashing and loops back to request input again.Now, the user must enter valid data before proceeding.
Here is the complete code for a more resilient program:
user_name = input('Enter your name: ')
while True:
try:
user_age = int(input('How old are you? '))
break
except ValueError:
print('Are you sure?')
continue
if user_age < 18:
print('Sorry, access is restricted to adults only')
else:
print('Welcome to the site,', user_name, '!')
input('Press Enter to go to the menu')
print('Welcome to the menu')
input('Press Enter to exit')
This program still allows unrealistic inputs (e.g., 3 meters tall or 300 years old). To enforce realistic values, additional range checks would be needed, but that is beyond the scope of this article.