Repotting a plant into a different pot

Type Casting

The analogy

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.

Visualizer

Repotting a value

step 1 / 6
VALUE โ€” and the pot it lives in
"12" (str โ€” two characters)

A user typed their age. It ARRIVED as text: the characters 1 and 2 standing side by side. No number in sight.

๐Ÿ“– In depth โ€” the full reference

Conversion table โ€” what casts to what

castinputresultrule
int("12")str12parses optional sign + digits; anything else โ†’ ValueError
int("7.5")strValueErrorint() does NOT parse decimals โ€” use int(float("7.5"))
int(3.9)float3TRUNCATES toward zero: int(-3.9) is -3
round(3.5)float4 (but round(2.5) is 2!)banker's rounding: ties go to the EVEN neighbour
float("2.5")str2.5accepts "inf", "nan", "1e3" too
str(42)int"42"never fails; repr() is its debugging sibling
bool(x)anythingFalse for 0, "", [], {}, Noneeverything else is True โ€” even "False" and [0]
int("ff", 16)str255second argument = base (2, 8, 16โ€ฆ)
3 + 0.5mixed3.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!"
Check yourself

What does int("7.5") do in Python?

Practice โ€” write it yourself

parse_plus_one(s) receives a NUMBER AS TEXT like "41". Cast it to a number and return one more. ("41" -> 42, not "411"!)

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser