Please enable JavaScript to use CodeHS

Python Tutorial

Casting in Python

The same value can wear different costumes: the string "42", the int 42, the float 42.0. Casting is how you switch between them, and it fixes some of the most common errors in Python.

python ~15 min Beginner friendly
The Big Idea

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:

main.py
zipcode = 11231
address = "23 State Street Brooklyn, NY "
print(address + zipcode)
Console
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 Toolkit

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:

str()

Constructs a string from the given value. Perfect for gluing numbers into messages.

str(11231) → "11231"
int()

Constructs an int from a float or a string. Decimal digits get chopped off!

int("42") → 42
float()

Constructs a float from an int or a string. Whole numbers gain a .0.

float(7) → 7.0
bool()

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:

main.py
zipcode = 11231
zipcode_string = str(zipcode)
address = "23 State Street Brooklyn, NY "
print(address + zipcode_string)
Console
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!

Interactive

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.

Casting chamber

int(x)
float(x)
str(x)
bool(x)

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!


Watch Out

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.

main.py
number = 14.6
print(int(number))    # the .6 gets dropped, not rounded up
Console
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:

Truncation vs rounding
x = 3.50
int(x) chops
3
round(x) rounds
4

Your Turn

Practice: cats and dogs

1

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:

Expected output
I have 2 cats and 1 dog - 3 animals in total!
main.py
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.

solution.py
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!")
Console
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.


Automatic Mode

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.

main.py
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))
Console
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.


Real World

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.

main.py
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))
Console (if the user types 12)
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.


Check Yourself

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.