Python Tutorial · Python Basics · Lesson 8 of 42
Python Casting
Convert between types with int(), float(), str() and bool().
Converting types
Use the type's constructor to convert a value:
print(int("42") + 1)
print(float("3.5"))
print(str(10) + " apples")
print(int(3.99))
print(round(3.99))
Output
43 3.5 10 apples 3 4
Common gotchas
int("3.9")fails — convert tofloatfirst, then toint.int()truncates towards zero; useround()to round.- Text from users, files and APIs is always a
str— convert before doing math.
price = "19.99"
quantity = "3"
total = float(price) * int(quantity)
print(total)
print(round(total, 2))
Output
59.97 59.97
Handling invalid input
Converting invalid text raises a ValueError. Catch it with try/except (covered later):
try:
age = int("twenty")
except ValueError as error:
print("Not a number:", error)
Output
Not a number: invalid literal for int() with base 10: 'twenty'
Test yourself
What does int(3.99) return?
433.99Error
Show answer
Answer: 3
int() truncates the decimal part instead of rounding.