Sometimes you need to convert data from one type to another. Python provides built-in functions for this, known as type casting:

FunctionPurposeExample
int()Convert to integerint("20")20
float()Convert to floatfloat("10.46")10.46
str()Convert to stringstr(100)"100"

Why Do We Need Type Conversions?

Consider this example:

print("10 + 20 = " + str(10 + 20))

Without str(), Python would try to concatenate a string and an integer, causing an error. The str() function converts the number 30 to the string "30" so it can be joined with the other text.

Common Conversions

String to Integer

age = int("20")      # converts the string "20" to the integer 20
print(age + 5)       # prints 25

Truncating with int()

The int() function also truncates floats by removing the decimal part:

print(int(10.8))     # prints 10
print(int(3.99))     # prints 3

String to Float

price = float("10.46")
print(price)         # prints 10.46

Fix the Code

Each of the following lines has a type error. Add the appropriate type conversion function to make it work.

1. print("The answer is " + 42)

Convert the integer to a string:

print("The answer is " + str(42))
2. print("20" + "30") — should print 50

Convert the strings to integers before adding:

print(int("20") + int("30"))
3. print("Half of 5 is " + 5 / 2)

Convert the division result to a string:

print("Half of 5 is " + str(5 / 2))
4. print("Total: " + 1 + int("20") + float("5.5"))

Calculate first, then convert the total to a string:

print("Total: " + str(1 + int("20") + float("5.5")))