Sub topic 4
Turning input text into numbers
This chapter assumes you can run a Python script and know the basic types str, int and float. It also assumes you have used if, while, and try/except. Retry loops get their own chapter, so here we focus on what conversion accepts, what it rejects, and where it surprises people.
Why input() needs conversion
input() always returns a str, whatever the user types. Typing 2 gives you the one-character string "2", not the number 2. Adding two such values joins them:
a = input("First number: ")
b = input("Second number: ")
print(a + b)If the user enters 2 and 3, this prints 23. Comparisons fail differently. "5" > 3 raises TypeError because Python will not order a string against an integer. Convert first:
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b)What int() and float() accept
Both functions call a parser on the string. The parser is more forgiving than you might expect in some ways and stricter in others. Run this to see it directly:
samples = ["42", " 42 ", "-7", "1_000", "3.5", "1,234", "", "1e3", "nan"]
for s in samples:
for conv in (int, float):
try:
result = conv(s)
except ValueError:
result = "ValueError"
print(f"{conv.__name__}({s!r}) -> {result}")The results, summarized:
| Text | `int()` | `float()` |
|---|---|---|
| `"42"` | 42 | 42.0 |
| `" 42 "` | 42 | 42.0 |
| `"-7"` | -7 | -7.0 |
| `"1_000"` | 1000 | 1000.0 |
| `"3.5"` | ValueError | 3.5 |
| `"1,234"` | ValueError | ValueError |
| `""` | ValueError | ValueError |
| `"1e3"` | ValueError | 1000.0 |
| `"nan"` | ValueError | nan |
Points worth remembering:
- Leading and trailing whitespace is ignored, including the newline in
"42\n". You rarely need.strip()just to make conversion work, though it is harmless. - A leading
+or-is allowed. - Underscores between digits are allowed, as in source code literals. A user typing
1_000gets 1000. int()rejects anything with a decimal point or exponent, even"3.0". It only parses integer text.- Thousands separators such as commas are never accepted.
- An empty string, which is what
input()returns when the user just presses Enter, raisesValueError.
The error message includes the offending text, for example invalid literal for int() with base 10: '3.5'. That is useful in logs, and you can catch the exception and show your own message instead.
Converting decimal text to an integer
Suppose you want a whole number but the user might type 3.7. Going through float works, but you must choose how to drop the fraction:
raw = "-3.9"
value = float(raw)
print(int(value)) # truncates toward zero
print(round(value)) # nearest integer
print(round(2.5)) # ties go to the even neighbor
print(round(3.5))This prints -3, -4, 2, and 4. int() truncates toward zero, so -3.9 becomes -3, not -4. round() uses round-half-to-even, so 2.5 becomes 2 and 3.5 becomes 4. Pick the rule that matches your domain and say so in a comment.
The float route also loses precision for large integers. A float has 53 bits of mantissa, so integers beyond 2**53 may not survive:
print(int(float("9007199254740993")))
print(int("9007199254740993"))The first line prints 9007199254740992, which is off by one. The second prints the exact value. If the text should be an integer, use int() directly and reject decimals instead of silently converting them.
Other bases
int() takes an optional second argument, the base:
print(int("ff", 16))
print(int("101", 2))
print(int("0x1f", 0))
print(int("0b101", 0))This prints 255, 5, 31, and 5. Base 0 means "read the prefix": 0x for hexadecimal, 0o for octal, 0b for binary. With base 0, a string like "010" raises ValueError, because leading zeros are not allowed in that mode. With the default base 10, "010" converts to 10.
Money and exact decimals
float stores binary fractions, so many decimal values are only approximate:
from decimal import Decimal
print(0.1 + 0.2 == 0.3)
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))This prints False and then True. For prices, tax, and anything that must match a decimal ledger, convert the input text straight to Decimal. Always pass a string. Decimal(0.1) would capture the already-inexact float.
Be aware of two differences from int() and float():
- A bad string raises
decimal.InvalidOperation, which is not a subclass ofValueError. Anexcept ValueErrorclause will not catch it. CatchInvalidOperationorArithmeticError. Decimal("nan")andDecimal("Infinity")are accepted, just as they are forfloat.
Values that parse but should not
float("nan"), float("inf") and float("-infinity") all succeed, in any letter case. A user who types nan into a "price" prompt gets a value that is not equal to itself and that makes every comparison False. If your program expects real quantities, check:
import math
def read_float(prompt: str) -> float:
value = float(input(prompt))
if not math.isfinite(value):
raise ValueError(f"finite number required, got {value}")
return valueBecause the function raises ValueError for both unparseable text and non-finite values, a caller needs only one except clause. Wrapping that call in a retry loop is the subject of the next chapter.
The parser also accepts digits from other scripts. int("٣"), using an Arabic-Indic digit, returns 3. That is usually fine. If you must restrict input to ASCII digits, test raw.isascii() and raw.isdigit() before converting. Note that str.isdigit() alone is not a safe test either, because it returns True for characters like "²" that int() rejects.
Locale and formatted numbers
People type numbers the way they write them. In much of Europe 1.234,5 means 1234.5. Python's int() and float() do not read locale conventions, so float("3,5") fails. Stripping commas with raw.replace(",", "") handles 1,234.5 but turns 3,5 into 35, which is silently wrong. Decide which convention your program supports. Reject anything else, or use the locale module's atof() after setting a locale deliberately.
bool() is not a parser
A common mistake when reading yes/no input is bool(input(...)). Any non-empty string is truthy, so bool("False") and bool("no") are both True. Compare against known words instead:
answer = input("Continue? (y/n) ").strip().lower()
proceed = answer in {"y", "yes"}
print(proceed)Checklist for converting input
- Pick the narrowest type that fits:
intfor counts,Decimalfor money,floatfor measurements. - Convert immediately after
input()and keep the raw string only for error messages. - Handle
ValueError, plusInvalidOperationif you useDecimal. - Apply range and finiteness checks after conversion.
- Decide explicitly how to treat decimals typed into an integer prompt: reject, truncate, or round.
Exercise
A user enters -2.8 at a prompt. What do int(float(raw)) and round(float(raw)) return, and why does int(raw) fail?
Show answer
int(float("-2.8")) returns -2 because int() truncates toward zero. round(float("-2.8")) returns -3, the nearest integer. int("-2.8") raises ValueError because int() only parses integer text, and "-2.8" contains a decimal point.
Exercise
Write a function read_price(prompt) that returns a Decimal built from user input, accepts only finite values, and raises ValueError for any bad text. Why is catching only ValueError around a bare Decimal(raw) call not enough?
Show answer
Use this:
from decimal import Decimal, InvalidOperation
def readprice(prompt):
raw = input(prompt).strip()
try:
value = Decimal(raw)
except InvalidOperation:
raise ValueError(f"not a number: {raw!r}") from None
if not value.isfinite():
raise ValueError(f"finite number required: {raw!r}")
return value
Decimal signals bad text with decimal.InvalidOperation, which is not a subclass of ValueError, so a bare except ValueError would let the error escape. The is_finite() check rejects nan and Infinity, which Decimal accepts.