Level 1
0 / 100 XP

Casting

Python casting is a way to specify the type of a variable you are declaring. This could come in handy when you want to ensure a variable that you receive is a number that you can do math operations with.

To help you understand this, let’s take an example of when things can go wrong in this scenario, when we want to add 3 + 1, which we would expect to equal 4:

Python
x = "3" y = "1" print(x + y)

The actual result is 31. This is because we are taking two strings and combining them. This would be an easy fix by simple removing the quotes from the X and Y variables like so:

Python
x = 3 y = 1 print(x + y)

This code prints the number 4 just like we want. Perfect, right? Kind of... Sometimes we cannot control the data that is handed to our application. Take for instance if we are receiving data from a third party or an API.

If we want to ensure that they pass a number to us and not a string, we can use Python casting to solve do this for us like so:

Python
x = int("3") y = int("1") print(x + y)

This outputs the bad, “31” value. Let’s update our add_numbers function to cast the variables to integers:

Python
def add_numbers(x, y): # Cast variables to int x = int(x) y = int(y) print(x + y) add_numbers("3", "1") add_numbers("3", 1) add_numbers(3, 1)

This will return 4 three different times because we are calling our add_numbers function 3 times with different mismatched strings and integers.