Python User Input
So far our programs always printed the same thing. With input, a program can ask the user a question and use the answer. input shows a prompt, waits until the user types a line and presses Enter, and returns what was typed as a string. In our editor you type the answer in the terminal, just as you would on a computer.
Asking a question
name = input("What is your name? ")
print(f"Hello, {name}!")Asha
What is your name? Hello, Asha!
The output box shows only what the program prints: the prompt and the greeting. In the terminal you also see the name you typed after the prompt. End the prompt with a space so the answer does not stick to the question.
Numbers need converting
input always returns text, even when the user types digits. To calculate, convert the answer with int or float:
a = int(input("First number: "))
b = int(input("Second number: "))
print(f"{a} + {b} = {a + b}")
print(f"{a} / {b} = {a / b:.2f}")7 3
First number: Second number: 7 + 3 = 10 7 / 3 = 2.33
Without the conversion, "7" + "3" would be "73": two pieces of text joined together. This is the most common surprise for beginners, and our editor's hint mentions it whenever text and numbers are mixed.
Several values on one line
To read several values typed on one line, split the answer and convert each part:
line = input("Enter three marks: ")
marks = [int(x) for x in line.split()]
print("Total:", sum(marks), "Average:", sum(marks) / len(marks))70 85 90
Enter three marks: Total: 245 Average: 81.66666666666667
The bracket expression is a list comprehension; a later topic explains it. map(int, line.split()) does the same job.
Checking the input
Users make mistakes. If they type ten where a number is expected, int raises a ValueError and the program stops. You can check first with isdigit, or catch the error with try and except as the Try ... Except topic shows, and ask again until the answer is valid.
Practice exercises
- Ask for the user's name and city and print one sentence with both.
- Ask for the length and width of a rectangle and print its area and perimeter.
- Ask for a temperature in Celsius and print it in Fahrenheit (
c * 9 / 5 + 32), rounded to one decimal. - Ask for three numbers on one line and print the largest with
max.