Converting between strings and numbers
Data that arrives as text — from a file, a web form, a request, the keyboard — is a string, even when it looks like a number. The string "42" is text; you can't add 1 to it directly.
To do maths you convert (or *cast*) it with int() (whole numbers) or float() (decimals). To go the other way — turn a number into text, e.g. to glue it into a message — use str().
These are *type conversion functions*: hand them a value, get back the same value as a different type. int("42") → 42, str(42) → "42", float("3.5") → 3.5.
Syntax
int("42") # 42 (str → int)
float("3.5") # 3.5 (str → float)
str(42) # "42" (int → str)
int(3.9) # 3 (float → int, truncates toward zero)Worked examples
Read text, convert, do maths
raw = "42" # came in as text
n = int(raw) # now a number
print(n + 1) # 43Number to text, then join
count = 7
msg = "You have " + str(count) + " items"
print(msg)
# Output:
# You have 7 itemsint() truncates a float (it does NOT round)
print(int(3.9)) # 3 (chops the decimal, not 4)
print(int(-3.9)) # -3 (toward zero)
print(round(3.9)) # 4 (use round() to round)Common mistakes & gotchas
int() of non-numeric text crashes
int("hello") raises ValueError: invalid literal for int() with base 10. So does int("3.5") — int() won't parse a decimal string. For "3.5" use float("3.5"), or int(float("3.5")) to then truncate.
Concatenating a number to a string
"You have " + 7 raises TypeError — you can't add a str and an int. Convert first with str(7), or sidestep the whole thing with an f-string: f"You have {7} items".
int() truncates, round() rounds
If you want 3.9 → 4 you need round(), not int(). int() always drops the fractional part toward zero, so int(3.9) is 3 and int(-3.9) is -3.
Why it matters
The boundary between your program and the outside world is almost always text. Every form field, log entry, CSV cell and API payload starts life as a string — converting cleanly (and handling the values that won't convert) is a daily backend task.