Explain it simply
Explain it simply
When you press a calculator's buttons, what reaches the machine is not a number but the symbols "1" and "0"; it converts them before adding. Python's input() works the same way: everything the user types arrives as text (str).
So a program that adds two numbers has three steps: turn the text into numbers (parse), add them (add) and show the result (format). You also have to decide in advance what happens when text like "ten" arrives instead of a number.
Problem → Why → Solution
The problem: 10 + 20 = 1020
A first "add two numbers" program reads two values with input() and adds them straight away. The user types 10 and 20 and gets 1020 instead of 30, with no error at all.
Wrapping the values in int() gives 30, until someone types 2.5 and the whole program stops with ValueError: invalid literal for int(). Adding try/except does not help by itself, either: if the try block contains only fixed values like a, b = 50, 60, nothing in it can fail, so the except branch never runs.
a = input("First number: ") # user types 10
b = input("Second number: ") # user types 20
print(a + b) # 1020 - string concatenation
total = int(a) + int(b) # works for 10 and 20 ...
# ... but int("2.5") or int("ten") raises ValueError and the program diesWhy does this happen?
The + operator changes meaning with the types of its operands: two numbers are added, two strings are joined, two lists are joined. input() always returns str, so without a conversion you get joining. And int() refuses text with a decimal point such as "2.5", raising ValueError.
Core concept: separate parse, add and format
"Adding" actually hides four decisions: which types are accepted, how text is converted, how much precision is needed, and what happens to bad input. Mixing them into one function makes it hard to test, so give each step its own place.
1. Parse: from text to a number
Use int() when only whole numbers are allowed and float() when decimals are. Both ignore surrounding spaces, so " 12 " is fine. Note that float() also accepts "nan" and "inf". A failed parse raises ValueError, and this is the step where you catch it.
2. Add: a pure function that only sees numbers
add_numbers(x, y) contains no input() and no print(): two numbers in, one number out. That means a one-line test such as assert add_numbers(2, 3) == 5 covers it, and a CLI, a GUI or a web API can all reuse it. Type hints help editors and type checkers but are not enforced at runtime; add_numbers("a", "b") would happily return "ab".
3. Precision: float or Decimal?
float is binary floating point and cannot store 0.1 exactly, which is why 0.1 + 0.2 is 0.30000000000000004. For science and measurements that is fine; for money, build Decimal("0.1") from a string. Building it from a float, as in Decimal(0.1), copies the float's error along with it.
4. Format: make the result readable
Apply formatting such as f"{total:.2f}" only when displaying. Rounding inside the calculation lets errors pile up in later calculations.
| Expression | Result | Why |
|---|---|---|
| 2 + 3 | 5 (int) | Two ints give an int |
| 2 + 3.0 | 5.0 (float) | The int is widened to float automatically |
| "2" + "3" | "23" | Two strings are joined |
| "2" + 3 | TypeError | Python never converts str and int implicitly |
| Decimal("2") + 0.5 | TypeError | Decimal and float refuse to mix |
- input() only ever gives str
- Parse, and catch errors right here
- Add numbers, nothing else
- Format only when displaying
Strings live only at the edges of the program; the middle works purely with numbers.
General pattern
def parse(text: str) -> float:
return float(text) # raises ValueError on bad text
def add(x: float, y: float) -> float:
return x + y # pure: no input(), no print()
try:
result = add(parse(raw_a), parse(raw_b))
except ValueError:
result = None # decide what bad input meansParsing raises, adding only ever sees numbers, and the try/except wraps the place where parsing is called.
Example: conversion, validation and precision
The program cannot read a keyboard here, so the strings input() would return are written in directly as typed_a and typed_b. add_from_text() handles parsing and errors, while add_numbers() only adds numbers. Both are written with def: PEP 8 recommends a def rather than assigning a lambda to a name.
from decimal import Decimal
# ===== 1. Plain numbers =====
a = 5
b = 7
print(f"{a} + {b} = {a + b}")
# ===== 2. input() always returns str =====
print("\n===== Text from input() =====")
typed_a, typed_b = "10", "20" # what input() would hand you
print(f"Without conversion: {typed_a + typed_b}")
print(f"With int(): {int(typed_a) + int(typed_b)}")
# ===== 3. Parse, then add, then format =====
def add_numbers(x: float, y: float) -> float:
return x + y
def add_from_text(first: str, second: str) -> str:
try:
x, y = float(first), float(second)
except ValueError:
return f"Error: {first!r} or {second!r} is not a number"
return f"{x} + {y} = {add_numbers(x, y)}"
print("\n===== Validated input =====")
print(add_from_text(" 12.5", "7.5 "))
print(add_from_text("ten", "5"))
# ===== 4. Floats versus Decimal =====
print("\n===== Precision =====")
print(f"0.1 + 0.2 = {0.1 + 0.2}")
print(f"Decimal: {Decimal('0.1') + Decimal('0.2')}")Code breakdown
- Strings join, numbers add
print(f"Without conversion: {typed_a + typed_b}")typed_a and typed_b are str, so + glues "20" onto "10" and produces "1020". The next line converts with int() first and gets 30.
- Parsing inside try
x, y = float(first), float(second)Only the conversion that can raise ValueError sits inside try. float() accepts text with spaces like " 12.5" and rejects "ten".
- Helpful error message
return f"Error: {first!r} or {second!r} is not a number"!r shows the user's text in quotes, so stray spaces or an empty string are visible. The program returns a message instead of crashing.
- Pure addition
return x + yadd_numbers() does one thing: addition. It can be tested without any input().
- Exact decimal arithmetic
print(f"Decimal: {Decimal('0.1') + Decimal('0.2')}")Building Decimal from strings keeps 0.1 exact, so the sum is 0.3, while the float version prints 0.30000000000000004.
5 + 7 = 12
===== Text from input() =====
Without conversion: 1020
With int(): 30
===== Validated input =====
12.5 + 7.5 = 20.0
Error: 'ten' or '5' is not a number
===== Precision =====
0.1 + 0.2 = 0.30000000000000004
Decimal: 0.3Wiring up the interactive version
Once the pure functions exist, input() belongs only at the outermost layer. To keep asking until the user types a valid number, parse inside a while True loop, print a message and continue on ValueError, and break on success.
With this split, testing the logic needs no keyboard, and the interactive part shrinks to a few lines with little room for mistakes. The read parameter below defaults to input, but the demo passes a function that replays prepared answers, so even the retry loop can be tested.
def ask_number(prompt: str, read=input) -> float:
while True:
text = read(prompt)
try:
return float(text)
except ValueError:
print(f"{text!r} is not a number, please try again.")
answers = iter(["ten", "12.5"]) # stands in for a real user
print(ask_number("First: ", read=lambda prompt: next(answers)))bool is an int too
In Python bool is a subclass of int, so True + True is 2. If a function checks types at runtime, remember that isinstance(x, int) accepts True and False as well.
In real projects
In real projects
Adding numbers sits inside every shopping-cart total, invoice, expense tracker and spreadsheet import. In those places the data arrives as text from a form, a CSV file or a JSON API, mixed with values like "1,000.50" with a thousands separator, empty cells and placeholders such as "N/A".
For money, most teams build Decimal values from strings; others store whole cents as int (1999 means 19.99). They also refuse to add amounts in different currencies. Test the parse function with a table of cases, writing down in advance what should happen for "10", " 2.5 ", "", "abc", "1e3" and "nan". Watch out for regional formats as well: in much of Europe "1.000,50" means one thousand and a half, and a naive parser reads it completely differently.
Common mistakes
Common mistakes
Wrapping code that cannot raise in try
If the try block only contains fixed values like a, b = 50, 60, the except ValueError branch can never run: it looks like error handling but protects nothing. Put the conversion, int() or float(), inside try and test it with input like "ten".
Converting decimal input with int()
int("2.5") does not return 2; it raises ValueError. Use float() or Decimal() if decimals are allowed. int(float("2.5")) gives 2, but it truncates the fraction, so use it only when that is really what you want.
Doing money arithmetic with float
Summing hundreds of cart items as floats can drift by a cent or so, and the totals stop matching the accounting report. Use Decimal("19.99") or integer cents.
Mini challenge
Total an expense list with Decimal
Add up a list of amount strings copied from a spreadsheet. parse_amount() turns one string into a Decimal; total_amounts() adds the valid ones and collects the invalid entries in an error list.
- Accept thousands separators such as "1,000.50" and surrounding spaces
- Skip blank entries without reporting an error
- Report "abc" and "NaN" in the error list
- Return a (total, errors) tuple and never call input()
from decimal import Decimal, InvalidOperation
def parse_amount(text: str) -> Decimal:
"""' 12.50 ' -> Decimal('12.50'); raise ValueError for bad input."""
# TODO: strip spaces and remove thousands separators
# TODO: Decimal(...) raises InvalidOperation -> re-raise as ValueError
# TODO: reject NaN and Infinity (Decimal.is_finite())
...
def total_amounts(entries: list[str]) -> tuple[Decimal, list[str]]:
"""Add every valid entry; skip blanks; collect bad entries."""
# TODO: start from Decimal("0"), loop, skip blanks, collect errors
...
# TODO: total the list ["19.99", " 0.01", "", "1,000.50", "abc", "NaN"]
# TODO: print the total, the errors, and the result for an empty listExpected: Total: 1020.50, with two error messages for 'abc' and 'NaN'. The empty list returns (Decimal('0'), []).
Show hint
Decimal("abc") raises decimal.InvalidOperation, not ValueError. Convert it with raise ValueError(...) from None so callers only have one exception type to catch.
Show solution
from decimal import Decimal, InvalidOperation
def parse_amount(text: str) -> Decimal:
"""' 12.50 ' -> Decimal('12.50'); raise ValueError for bad input."""
cleaned = text.strip().replace(",", "")
try:
amount = Decimal(cleaned)
except InvalidOperation:
raise ValueError(f"not a number: {text!r}") from None
if not amount.is_finite():
raise ValueError(f"not a finite amount: {text!r}")
return amount
def total_amounts(entries: list[str]) -> tuple[Decimal, list[str]]:
"""Add every valid entry; skip blanks; collect bad entries."""
total = Decimal("0")
errors = []
for entry in entries:
if not entry.strip():
continue
try:
total += parse_amount(entry)
except ValueError as error:
errors.append(str(error))
return total, errors
total, errors = total_amounts(["19.99", " 0.01", "", "1,000.50", "abc", "NaN"])
print(f"Total: {total}")
print(f"Errors: {errors}")
print(total_amounts([]))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- input() always returns str, so convert with int(), float() or Decimal() before adding
- + adds numbers but joins strings and lists
- Catch ValueError where conversion happens, and keep input() at the outermost layer
- For money, use Decimal built from strings, or integer cents
The Python Tutorial — Python Software Foundation