Type Casting in Python

Ever tried to add a number to a word and got a crash? Let’s learn how to tell Python exactly what kind of data we're working with!

01

What is Type Casting?

Think of Type Casting as a translator. Sometimes Python gets confused when you try to mix different data types—like adding text to a number. Casting lets us manually change a piece of data from one type (like a "string" of text) into another (like an "integer" number).

02

Doing it Yourself (Explicit)

This is when you, the programmer, take charge. If you have a string "15" and want to do math with it, you use:

number = int("15") # Now it's a real number!

Note: If you try int("Hello"), Python will throw a ValueError because it doesn't know how to turn "Hello" into a number!

03

Python's Smart Helpers (Implicit)

Sometimes, Python is smart enough to change the data type for you automatically. If you add an integer (like 5) and a float (like 2.5), Python will turn the 5 into a 5.0 so the math stays accurate. This is called "implicit" casting because Python does the heavy lifting to prevent data loss.