Python User Input
What you will learn
- How to ask the user a question with
input() - Why the answer is always text
- How to convert the answer to a number
- How to read several values from one line with
split() - How to clean text with
strip()andlower() - What goes wrong with bad input
1. The input() function
input() shows a prompt, waits for the user to type and press Enter, and gives back what they typed:
name = input("What is your name? ")
print("Hello,", name)
Run it. The lines below show how it looks in a terminal, where the user's typing is the text after each question:
What is your name? Rina
Hello, Rina
The text in the brackets is the prompt. End it with a space, as in "What is your name? ", so the answer does not touch the question. You can also call input() with no prompt at all.
input() only works when a person can type into the program. Run your file in a terminal (lesson 1.4). Some editors' output windows cannot accept typing, and then the program stops with an EOFError.
Quick check: where does the typed answer go?
It becomes the value that input() gives back. Store it in a name, as with name = input(...), or you cannot use it afterwards.
2. The answer is always text
Even when the user types digits, input() returns a string:
age = input("Age: ")
print(type(age), age + "1")
If the user types 25:
<class 'str'> 251
age + "1" joined the text "25" and "1". It did not add numbers. This is the most common beginner surprise.
3. Converting the answer to a number
Wrap input() in int() for a whole number or float() for a decimal number (lesson 2.4):
n = int(input("n: "))
print(n * 2)
If the user types 7:
n: 14
You can also do it in two steps: first text = input("n: "), then n = int(text). Doing it in one line is just shorter.
Choose the type by what the answer means:
| Answer is | Use | Example input |
|---|---|---|
| a whole number (age, count) | int(input(...)) |
25 |
| a number with decimals (price, height) | float(input(...)) |
84.50 |
| text (name, city) | input(...) alone |
Rina |
4. Several values on one line
input().split() cuts the typed text at the spaces and gives a list of pieces. You can unpack the pieces into names (lesson 2.1):
a, b = input("Two numbers: ").split()
print(a, b, type(a))
print(int(a) + int(b))
If the user types 3 4:
Two numbers: 3 4
3 4 <class 'str'>
7
The pieces are still text, so each one is converted before adding. The number of names must match the number of pieces: typing three values into a, b = ... stops with ValueError: too many values to unpack (expected 2).
5. Cleaning the text
The user may add spaces or use capital letters. Two string methods help (more in chapter 4):
| Method | What it does | Example | Result |
|---|---|---|---|
.strip() |
removes spaces at the start and the end | " hi \n".strip() |
'hi' |
.lower() |
turns all letters into lower case | "Yes".lower() |
'yes' |
Chaining them cleans an answer in one line:
answer = input("Continue? ").strip().lower()
print(repr(answer))
If the user types YES (with spaces and capitals):
Continue? 'yes'
(repr shows the quotation marks, so you can see exactly what the text contains.) Now a comparison with "yes" works however the user typed it.
If the user just presses Enter, input() gives back an empty string, ''.
6. When the input is wrong
Python cannot know whether the user typed a sensible answer. Typing the wrong thing into int(input(...)) stops the program:
age = int(input("Age: "))
| User types | Result |
|---|---|
25 |
works: 25 |
abc |
ValueError: invalid literal for int() with base 10: 'abc' |
3.5 |
ValueError: invalid literal for int() with base 10: '3.5' |
Checking input and asking again is covered later: decisions in chapter 5, repeating in chapter 6 and catching errors in chapter 14. For now, keep your programs simple and type sensible answers.
Worked example: a tip calculator
The program asks for a bill and a tip percentage, and shows the tip and the total.
bill = float(input("Bill: "))
tip = int(input("Tip percent: "))
tip_amount = bill * tip / 100
total = bill + tip_amount
print(f"Tip: {tip_amount:.2f}")
print(f"Total: {total:.2f}")
If the user types 84.50 and 10:
Bill: 84.50
Tip percent: 10
Tip: 8.45
Total: 92.95
| Step | What happens |
|---|---|
| 1 | float(input(...)) turns "84.50" into 84.5 |
| 2 | int(input(...)) turns "10" into 10 |
| 3 | tip = 84.5 × 10 ÷ 100 = 8.45 |
| 4 | total = 84.5 + 8.45 = 92.95 |
| 5 | :.2f in the f-string shows exactly 2 decimals |
Common mistakes
- Adding without converting.
input("A: ") + input("B: ")joins the text; useint(...)orfloat(...). - Forgetting to store the answer.
input("Name: ")alone throws the answer away. - Using
int()for a decimal answer.int("3.5")fails; usefloat(...). - Forgetting that the text may have spaces or capitals. Clean it with
.strip()and.lower()before comparing. - Running the program where typing is impossible, which gives
EOFError. Use a terminal.
Key takeaways
input(prompt)waits for the user and returns what they typed as text.- Convert with
int(input(...))orfloat(input(...))before doing arithmetic. input().split()splits one line into several pieces, which are still text..strip()and.lower()clean an answer before you compare it.- Wrong input stops the program with a
ValueError; checking input comes in later chapters.
Practice
1. What does this print if the user types 4: x = input("x: ") then print(x * 3)?
Show answer
444. The answer is text, so * repeats it. Use int(x) * 3 to get 12.
2. Write two lines that ask for a price and show the price with 10 added.
Show answer
price = float(input("Price: ")) then print(price + 10).
3. The user types 5 8 into a, b = input().split(). What are the types and values of a and b? How do you get their sum?
Show answer
Both are text: "5" and "8". The sum is int(a) + int(b), which gives 13.
4. The user types Dhaka with spaces. Which line stores dhaka with no spaces?
Show answer
city = input("City: ").strip().lower().
5. What error appears if the user types ten into int(input("Number: "))?
Show answer
ValueError: invalid literal for int() with base 10: 'ten'.
6. Write a program that asks for a width and a height (decimals allowed) and shows the area.
Show answer
For example: w = float(input("Width: ")), h = float(input("Height: ")), print(w * h).