Type Casting
Sometimes a value arrives in the wrong kind of box. A user types their age and it lands as the TEXT "12" โ two characters, not a number. Try "12" + 1 and the machine refuses: you cannot add a number to text. Casting is repotting: int("12") lifts the value out of the text pot and settles it into a number pot, and NOW maths works. Some repottings lose soil on purpose โ int(3.9) is 3, not 4; the decimal part is simply cut off, never rounded. And some are impossible: int("hello") has no number inside to lift out, so the program raises an error instead of guessing.
Repotting a value
step 1 / 6A user typed their age. It ARRIVED as text: the characters 1 and 2 standing side by side. No number in sight.
Conversion table โ what casts to what
| cast | input | result | rule |
|---|---|---|---|
| int("12") | str | 12 | parses optional sign + digits; anything else โ ValueError |
| int("7.5") | str | ValueError | int() does NOT parse decimals โ use int(float("7.5")) |
| int(3.9) | float | 3 | TRUNCATES toward zero: int(-3.9) is -3 |
| round(3.5) | float | 4 (but round(2.5) is 2!) | banker's rounding: ties go to the EVEN neighbour |
| float("2.5") | str | 2.5 | accepts "inf", "nan", "1e3" too |
| str(42) | int | "42" | never fails; repr() is its debugging sibling |
| bool(x) | anything | False for 0, "", [], {}, None | everything else is True โ even "False" and [0] |
| int("ff", 16) | str | 255 | second argument = base (2, 8, 16โฆ) |
| 3 + 0.5 | mixed | 3.5 (float) | implicit promotion: int โ float in mixed arithmetic โ the ONLY implicit coercion Python does |
The rules
- Python is strongly typed: "12" + 1 raises TypeError instead of guessing. Every other conversion must be explicit.
- Casting never mutates โ int(x) returns a NEW value; x is untouched.
- Truncation vs rounding is a business decision: int() cuts, round() uses banker's rounding, math.floor/ceil go down/up. Pick deliberately.
- Wrap boundary casts: try: n = int(raw) / except ValueError: complain. Users type "twelve".
- bool("False") is True โ non-empty strings are truthy. Parse flags explicitly: raw.lower() in ("true", "1", "yes").
raw = input() # user types 12 -> "12" (a string!)
age = int(raw) # cast: "12" -> 12
print(age + 1) # 13
print(int(3.9)) # 3 (truncates, never rounds)
print(float("2.5")) # 2.5
print(str(42) + "!") # "42!"What does int("7.5") do in Python?
parse_plus_one(s) receives a NUMBER AS TEXT like "41". Cast it to a number and return one more. ("41" -> 42, not "411"!)