Last updated
Python Casting
Definition: Casting (or type conversion) means changing a value from one type to another — for example turning the text "10" into the number 10.
The conversion functions
int(x)— convert to a whole numberfloat(x)— convert to a decimal numberstr(x)— convert to text
Example 1 — text to number and back
a = int("10") # "10" -> 10
b = float("3.5") # "3.5" -> 3.5
c = str(99) # 99 -> "99"
print(a + 5)
print(b)
print(c + "!")
Example 2 — why it is needed
Numbers typed by a user arrive as text. You must cast before doing maths:
price = "20"
qty = "3"
total = int(price) * int(qty)
print("Total:", total)
Without int(), "20" * "3" would error.
Example 3 — number to text for joining
You cannot join text and a number with +, so convert the number first:
age = 25
print("I am " + str(age) + " years old")
💡 Watch out: int("hello") fails — you can only convert text that actually looks like a number.
Try it Yourself
Output
Ad · responsive