Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

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}!")
You type
Asha
Output
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}")
You type
7
3
Output
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))
You type
70 85 90
Output
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

  1. Ask for the user's name and city and print one sentence with both.
  2. Ask for the length and width of a rectangle and print its area and perimeter.
  3. Ask for a temperature in Celsius and print it in Fahrenheit (c * 9 / 5 + 32), rounded to one decimal.
  4. Ask for three numbers on one line and print the largest with max.