Wrap input() directly in int(...) or float(...)—for example, age = int(input("Enter age: ")) or price = float(input("Enter price: "))—because input() always returns a str in Python 3, and wrap the conversion in a try ... except ValueError loop whenever the user might enter non-numeric text, blank lines, or whitespace.
Basic Example
# 1. Direct single-line conversion (raises `ValueError` if input is non-numeric):
age = int(input("Enter your age: "))
price = float(input("Enter item price: "))
print(f"Age: {age} ({type(age).__name__}), Price: {price:.2f} ({type(price).__name__})")
# 2. Recommended: Safe validation loop that re-prompts on invalid input
def read_int(prompt: str) -> int:
while True:
raw = input(prompt).strip()
try:
return int(raw)
except ValueError:
print(f"'{raw}' is not a valid whole number. Try again.")
def read_float(prompt: str) -> float:
while True:
raw = input(prompt).strip()
try:
return float(raw)
except ValueError:
print(f"'{raw}' is not a valid number. Try again.")
count = read_int("Quantity: ")
weight = read_float("Weight (kg): ")
Key Details & Edge Cases
- Decimal strings fail inside
int("3.14")(ValueError):int()only parses whole-number strings (including signs and surrounding whitespace like" -42\n"). Passing"3.14"directly toint()raisesValueError: invalid literal for int() with base 10: '3.14'. Convert tofloat()first (int(float(raw))) if decimal strings should truncate toward zero.
float()accepts"nan","inf", and"-infinity"by default:float("nan")andfloat("inf")succeed without raisingValueError, which can break downstream comparisons or JSON serialization. Guard against non-finite floats usingmath.isfinite(val)(if not math.isfinite(val): raise ValueError(...)).
- Reading multiple numbers on a single space-separated line (competitive programming / CLI):
- Split the line with
.split()and mapintorfloatacross the tokens:width, height = map(int, input("Enter width and height: ").split()) scores = [float(x) for x in input("Enter scores: ").split()]
- Split the line with
- Never use
eval(input())to parse numbers:- Unlike Python 2’s legacy
input(),eval(input())executes arbitrary Python expressions entered by the user, creating a critical remote code execution (RCE) vulnerability. Always useint(),float(), ordecimal.Decimal()(for exact currency values).
- Unlike Python 2’s legacy
- Use
decimal.Decimalinstead offloatfor money/financial inputs:- Binary floating-point arithmetic introduces rounding artifacts (
0.1 + 0.2 == 0.30000000000000004). Pass the string frominput()directly intoDecimal(raw)(from decimal import Decimal, InvalidOperation) to preserve exact decimal precision.
- Binary floating-point arithmetic introduces rounding artifacts (
Comparison of Numeric Input Parsing Methods in Python
| Method | Accepted Input Examples | Rejects "nan" / "inf"? |
Exact Decimal Precision? | Best Used When |
|---|---|---|---|---|
int(input(prompt)) |
"42", " -7 " |
N/A (integers only) | Yes (arbitrary-precision int) |
Reading counts, ages, indices, or whole numbers. |
float(input(prompt)) |
"3.14", "-5", "1e-3" |
No (check math.isfinite()) |
No (IEEE 754 binary float) | Scientific measurements, ratios, coordinates, and general real numbers. |
Decimal(input(prompt)) (decimal module) |
"19.99", "-0.05" |
No (check .is_finite()) |
Yes | Currency amounts, prices, tax rates, and financial calculations. |
map(int, input().split()) |
"10 20 30" (single line) |
N/A | Yes | Reading multiple space-separated numbers from one input line. |
You must log in or register to comment.
