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:

Example 1Try it yourself
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 to float first, then to int.
  • int() truncates towards zero; use round() to round.
  • Text from users, files and APIs is always a str — convert before doing math.
Example 2Try it yourself
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):

Example 3Try it yourself
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?

  1. 4
  2. 3
  3. 3.99
  4. Error
Show answer

Answer: 3

int() truncates the decimal part instead of rounding.