Sometimes you need to convert data from one type to another. Python provides built-in functions for this, known as type casting:
| Function | Purpose | Example |
|---|---|---|
int() | Convert to integer | int("20") → 20 |
float() | Convert to float | float("10.46") → 10.46 |
str() | Convert to string | str(100) → "100" |
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.
age = int("20") # converts the string "20" to the integer 20
print(age + 5) # prints 25
int()The int() function also truncates floats by removing the decimal part:
print(int(10.8)) # prints 10
print(int(3.99)) # prints 3
price = float("10.46")
print(price) # prints 10.46
Each of the following lines has a type error. Add the appropriate type conversion function to make it work.
print("The answer is " + 42)Convert the integer to a string:
print("The answer is " + str(42))
print("20" + "30") — should print 50Convert the strings to integers before adding:
print(int("20") + int("30"))
print("Half of 5 is " + 5 / 2)Convert the division result to a string:
print("Half of 5 is " + str(5 / 2))
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")))