Reading Input From the User
Concepts covered: Functions
Every program so far had its values written into the code. input() lets the person running the program supply a value while it runs. The call shows its prompt text, pauses, waits for the user to type and press Enter, and then hands back whatever was typed. The program resumes on the next line with that text stored wherever you assigned it.
name = input("Your name: ")
print("Hello,", name)The prompt is ordinary text, so end it with a space or the cursor sits jammed against the colon. Whatever comes back is a string, every time. Type 42 and input returns "42", 2 characters that happen to be digits. Press Enter with nothing typed and it returns "", the empty string. Spaces typed before or after the value survive as well.
| User types | Value stored | Type |
|---|---|---|
| Maya | "Maya" | str |
| 42 | "42" | str |
| 3.5 | "3.5" | str |
| (Enter, nothing typed) | "" | str |
| 7 | " 7 " | str |
Adding a number to typed text
Treating that string as a number is the most frequent mistake in a first program with input. The program below stands in for a session where the user typed 30 at an Age prompt; the variable holds exactly what input would have returned, so the result is the same as the live version.
age = "30"
print(age + 1)Python refuses because + between a string and an int has no single meaning: join them, or add them? The message says which reading it took, concatenation, and what it could not accept, the int. Before any arithmetic, convert the text to a number with int() or float(). Each is a function that reads a string of digits and returns the matching numeric value.
age = "30"
age = int(age)
print(age + 1)
height = float("1.75")
print(height * 2)Output:
31 3.5
int() accepts digits with an optional leading sign and ignores spaces around them, so int(" 7 ") returns 7. float() accepts those plus a decimal point, so float("3") returns 3.0. Text that isn't a number, such as letters or, for int(), a decimal point, makes the conversion fail with a ValueError, the signal that the type was right and the content was wrong.
print(int(" 7 "))
print(float("3"))
print(int("ten"))The first 2 lines printed before line 3 failed, because a program runs every line up to the one that raises. int("3.5") fails the same way, since a decimal point is not a digit; convert through float() when the user may type a fraction.
The user types 7 at the prompt. What does this program print?
count = input("How many? ")
print(count * 3)- 21, because input returns an int when every character typed is a digit
- 73, because the 3 is attached to the end of the string
- 777, because count holds the string "7" and a string times 3 is the string repeated
- A TypeError, because a string cannot be multiplied by an int
Convert at the moment of reading
The usual shape wraps the input call directly in the conversion, so the variable never holds the raw string and no later line can forget to convert it.
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print("Total:", total)| Price typed | Quantity typed | Result |
|---|---|---|
| 2.50 | 4 | Total: 10.0 |
| 19.99 | 2 | Total: 39.98 |
| 5 | 2 | Total: 10.0 |
| abc | (never asked) | ValueError raised at line 1 |
| 2.50 | 1.5 | ValueError raised at line 2 |
The fourth row shows the program dying at line 1, so the Quantity prompt never appears. The last row shows that int() rejects a fraction even though a human would read 1.5 as a number. Checking the text before converting, and asking again when it fails, uses tools from a later lesson; for now the rule is that the conversion line is where bad input surfaces.
Practice
About this lesson
This section is part of the Python Foundations: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.