What is casting?
Casting is the process of converting a value of one type into a value of another type. Sometimes an operation only works when a value gets converted first - Python won't glue a number onto a string, for example, until you turn the number into a string.
Say a programmer wants to print their mailing address, but they stored their zip code as an int. Press Run and watch what happens:
zipcode = 11231 address = "23 State Street Brooklyn, NY " print(address + zipcode)
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(address + zipcode)
TypeError: can only concatenate str (not "int") to str
Crash! The program raises a TypeError because you can only add a str to another str. To print the zip code as part of the address, we need to convert it into a string first. That conversion is casting.
The casting functions
Luckily, converting basic data types in Python is simple. You pass the value through a constructor function named after the type you want:
Constructs a string from the given value. Perfect for gluing numbers into messages.
str(11231) → "11231"
Constructs an int from a float or a string. Decimal digits get chopped off!
int("42") → 42
Constructs a float from an int or a string. Whole numbers gain a .0.
float(7) → 7.0
Constructs True or False. Zero and empty things are False; everything else is True.
bool("") → False
To fix our broken program, we pass zipcode through the str() constructor function. You can also store the result in a new variable and use it later:
zipcode = 11231 zipcode_string = str(zipcode) address = "23 State Street Brooklyn, NY " print(address + zipcode_string)
23 State Street Brooklyn, NY 11231
Not everything can be cast: int("42") works because "42" looks like a number, but int("hello") raises a ValueError. Python can't guess what number "hello" is supposed to be!
The casting chamber
Type any value into the chamber and watch all four casting functions try to transform it at once. Some casts succeed, some change the value, and some crash spectacularly. Try the presets - a few of them hide surprises.
Did you catch the gotchas? int("3.9") crashes even though int(3.9) works - int() only accepts strings that look like whole numbers. And bool("False") is True, because any non-empty string counts as True!
int() truncates - it does not round!
Casting to str keeps the value looking exactly the same. But casting a float to an int can change the number: the decimal part gets dropped completely. Chopped off. Gone.
number = 14.6 print(int(number)) # the .6 gets dropped, not rounded up
14
This is called truncation. Even int(14.999) gives 14. If you actually want normal rounding, Python has a separate round() function. Drag the slider and watch the two functions disagree past the halfway point:
Practice: cats and dogs
Animal Census
The variables below are stored in awkward types: dogs is a string and cats is a float. Using casting (and only these two variables), produce exactly this output:
I have 2 cats and 1 dog - 3 animals in total!
dogs = "1" cats = 2.0 # Print "I have 2 cats and 1 dog - 3 animals in total!" # using the variables above and casting. print()
Hints: printing cats directly shows 2.0, not 2. And you can't add "1" and 2.0 to count the animals without converting something first.
dogs = "1" cats = 2.0 # int(cats) turns 2.0 into 2, int(dogs) turns "1" into 1 total = int(cats) + int(dogs) print("I have " + str(int(cats)) + " cats and " + dogs + " dog - " + str(total) + " animals in total!")
I have 2 cats and 1 dog - 3 animals in total!
Notice the double cast: int(cats) chops 2.0 down to 2, then str(...) makes it printable. Meanwhile dogs is already a string, so it can go straight into the message - but it needs int() before it can be added to count the total.
Implicit casting
Implicit casting is when Python converts a value automatically, without you writing any casting function. The most common example: when an int and a float meet in a math operation, the result is automatically a float.
num1 = 6 num2 = 5.7 # Math between a float and an int automatically # casts the result into a float num3 = num1 + num2 print(num3) print(type(num3))
11.7 <class 'float'>
The value of num3 became a float on its own - Python promoted the int 6 to 6.0 behind the scenes so nothing would be lost in the addition.
Casting input()
Here's where casting becomes something you use every single day: the input() function always returns a string, even if the user types a number. If you want to do math with what they typed, you have to cast it.
age = input("How old are you? ") # age is a str, like "12" age = int(age) # now it's a number print("Next year you will be " + str(age + 1))
How old are you? 12 Next year you will be 13
Casting happens twice here: int(age) converts the typed string into a number so we can add 1, then str(age + 1) converts the answer back into a string so it can be glued into the message.
Round trip: str → int → do math → str. You'll write this pattern constantly. There's a whole tutorial on it: User Input in Python.
Quick quiz
1. What does print(int(14.6)) output?
2. Which line fixes print("Score: " + 100)?
3. A user runs age = input("Age? ") and types 13. What type is age?
Keep learning Python
Casting turns values from one type into another. Next, put it to work on real user input, or review how variables and types work in the first place.