Sub topic 4
Turning input text into numbers
This chapter assumes you can run a Python script, know the built-in types str, int and float, and have used if statements and try/except. It covers what input() returns and how to convert that value into a number.
input() always returns a string
input() reads a line from the keyboard and returns it as a str. This is true even when the user types digits. The value "42" is text, not a number, so arithmetic on it either fails or does something you did not intend.
a = input("First: ")
b = input("Second: ")
print(a + b)If the user types 4 and then 5, this prints 45. The + operator joins two strings. It does not add them.
Converting with int() and float()
Pass the string to int() or float() to get a number.
raw = input("Quantity: ")
qty = int(raw)
print(qty * 2)Choose the function by the kind of number you expect:
| Function | Accepts | Rejects |
|---|---|---|
| `int("42")` | Whole numbers such as `"42"`, `"-7"`, `" 8 "` | `"3.5"`, `"abc"`, `""` |
| `float("3.5")` | Decimals and whole numbers such as `"3.5"`, `"2"`, `"1e3"` | `"abc"`, `""`, `"1,5"` |
Both functions ignore spaces at the start and end of the string. Both raise ValueError when the text is not a valid number.
The common error
The most frequent mistake is forgetting to convert. It shows up as a TypeError when you mix a number and a string.
age = input("Age: ")
print(age + 1)Typing 30 gives TypeError: can only concatenate str (not "int") to str. The fix is to convert once, as soon as you read the value.
age = int(input("Age: "))
print(age + 1)Wrapping input() inside int() is a common idiom. It is fine for quick scripts. If the user types something that is not a number, the program stops with a ValueError traceback. The next chapter shows how to catch that error and ask again.
What the conversion looks like
A worked example
This program reads a price and a quantity, converts each with the right type, and prints the total.
price = float(input("Unit price: "))
qty = int(input("Quantity: "))
total = price * qty
print(f"Total: {total:.2f}")With the inputs 2.5 and 4, it prints Total: 10.00. The price uses float because prices have fractions. The quantity uses int because you cannot buy half an item here.
Things to watch for
- Convert at the point of reading. Keep
rawas the string andqtyas the number, so you do not mix them up later. int("1,000")fails because of the comma. Remove it first withraw.replace(",", "").float("nan")andfloat("inf")are accepted and give special values. If you need ordinary numbers only, check the result before using it.- An empty answer (the user just presses Enter) gives
"", which raisesValueErrorin both functions.
Exercise
A user types 7.9 at the prompt n = int(input("n: ")). What happens, and how would you change the code so that the program accepts 7.9 and stores the whole number 7?
Show answer
int("7.9") raises ValueError because the text is not a whole number. Convert with float first and then truncate: n = int(float(input("n: "))). This stores 7.
Exercise
What does this code print if the user types 10 and then 20? x = input("x: "), y = input("y: "), print(x + y). Rewrite it so that it prints 30.
Show answer
It prints 1020, because both values are strings and + joins them. Convert each value with int(): x = int(input("x: ")) and y = int(input("y: ")). Then print(x + y) prints 30.