What type conversion is
Every value in Python has a type, such as int for whole numbers, float for numbers with a decimal part and str for text. Python does not guess when you mix them up. The number 25 and the text "25" look alike when printed, but they behave differently: you can add two numbers, and you can join two strings, but Python refuses to add a number to a string.
Type conversion means creating a value of one type from a value of another. In Python you do this by calling the type's name as a function. This is useful whenever data arrives in the wrong form, for example when you read a number from text, or when you need to put a number inside a message.
The three conversion functions
The three you need first are int(), float() and str():
print(int("100")) # 100
print(float("3.5")) # 3.5
print(float(7)) # 7.0
print(str(3.0)) # 3.0
print(str(True)) # True
None of these functions changes the original value. Each one builds and returns a new value, which you normally store in a variable. The original variable keeps its old value and its old type.
Converting to a string
str() accepts almost anything and gives back its text form. It is the standard way to put a number into a message:
print("Age: " + str(25)) # Age: 25
Without the conversion, "Age: " + 25 raises TypeError: can only concatenate str (not "int") to str.
Converting a float to an int
int() applied to a float throws away the decimal part. It does not round. It simply cuts the number off at the decimal point, which means it moves toward zero:
print(int(9.99)) # 9
print(int(3.1)) # 3
print(int(-9.99)) # -9
print(round(9.99)) # 10
This surprises many beginners: 9.99 becomes 9, not 10. If you want rounding, use the built-in round() instead.
Converting a string to a number
int() and float() read text and turn it into a number. The text must look like a number of the right kind. Spaces and a newline around the digits are allowed, and a leading minus sign is fine:
print(int("-5")) # -5
print(int(" 42 ")) # 42
print(float("2.50")) # 2.5
Common mistakes
- Converting text that is not a whole number.
int("3.7")raisesValueError: invalid literal for int() with base 10: '3.7'. The same error appears forint("abc")and for the empty string. When the text holds a decimal, go through a float first:int(float("3.7"))gives3. - Expecting
int()to round. It truncates toward zero, soint(-0.5)is0, andint(9.99)is9. - Forgetting to save the result. Writing
int(price)on a line by itself computes a value and throws it away. You must assign it, as inprice_int = int(price). - Mixing up text and numbers.
"5" + "5"is"55", whileint("5") + int("5")is10. If a calculation gives a strangely long result, check whether you are working with strings. - Thinking the variable changed type. After
age_str = str(age), the variableageis still an integer. Onlyage_stris a string.
The exercise, step by step
The lesson starts with three variables of three different types: an integer age, a float price and a string year. You add one new variable for each, converting it to a different type.
- Convert the integer to a string. Call
str()onageand store the result inage_str. The new variable holds the text"25". - Convert the float to an integer. Call
int()onpriceand store it inprice_int. Becauseint()drops the decimal part,9.99becomes9. - Convert the string to an integer. Call
int()onyearand store it inyear_int. The text"2024"is a valid whole number, so this works and gives the number2024.
age = 25
price = 9.99
year = "2024"
age_str = str(age)
price_int = int(price)
year_int = int(year)
To see what you got, print the values and their types:
print(repr(age_str), type(age_str))
print(price_int, type(price_int))
print(year_int + 1, type(year_int))
'25' <class 'str'>
9 <class 'int'>
2025 <class 'int'>
The last line shows why the conversion is worth doing: year could not take part in arithmetic, but year_int can. The original price is still 9.99 and year is still the string "2024".
Key takeaways
- Convert with
int(),float()andstr(). Each returns a new value and leaves the original alone. int()on a float drops the decimal part toward zero. Useround()when you want rounding.int()on text accepts only text that looks like a whole number, otherwise it raisesValueError.- Use
str()to place numbers inside text. - Always assign the result of a conversion to a variable if you want to keep it.