Python Casting

Convert between types.

✍️ 3 exercises + code challenge in this lesson

Casting means converting a value to another type using constructor functions:

  • int("10") → 10, int(3.9) → 3 (truncates)
  • float("2.5") → 2.5, float(3) → 3.0
  • str(42) → "42"
  • bool(0) → False

Converting an invalid string, like int("abc"), raises a ValueError.

Key Takeaways: Python Casting

Mastering Python Casting helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Casting Code Example

Python
print(int("10") + 5)
print(int(3.9))
print(float("2.5") * 2)
print(str(42) + " is the answer")
print(bool(0), bool(""), bool("hi"))

try:
    int("abc")
except ValueError as e:
    print("Error:", e)
Free sign-in required · Google login available

Python Casting Practice Exercises

Check what you learned in “Python Casting”.

/ 3 solved
Fill in the blank

Convert the string to an integer.

age = ("25")
✓ Correct! Not quite. Try again.
Multiple choice

What does int(9.99) return?

✓ Correct! Not quite. Try again.
Code challenge

Convert "10" and "5" to integers and print their sum.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services