Type Conversion
In this tutorial, we'll convert between strings, numbers, and booleans.
Type conversion means changing a value from one type to another.
This matters because Python treats different types differently:
print("5" + "5")
print(5 + 5)
Output:
55
10
The first line joins strings. The second line adds integers.
Converting to an Integer
Use int() to convert suitable text into a whole number:
age_text = "12"
age = int(age_text)
print(age + 1)
Output:
13
This only works if the string looks like an integer:
int("hello") # error
Converting to a Float
Use float() for decimal numbers:
price_text = "4.99"
price = float(price_text)
print(price * 2)
Converting to a String
Use str() when you need text:
score = 95
message = "Score: " + str(score)
print(message)
In print(), commas are often simpler:
print("Score:", score)
Input Always Starts as Text
When you later use input(), the result is always a string:
age = input("Age: ")
If you want maths, convert it:
age = int(age)
print(age + 1)
Practice
Start with price_text = "12.50" and quantity_text = "3". Convert them, calculate the total, and print it.