Python Casting (Type Conversion)
Casting means converting a value from one type to another. You need it all the time, because data often arrives as text: everything a user types with input, every line read from a file and every value in a CSV table is a string, even when it looks like a number. Before you can calculate with it, you convert it.
The conversion functions
Each built-in type has a function with the same name that converts a value to that type:
print(int("42") + 1) # text to a whole number
print(float("3.5") * 2) # text to a decimal number
print(str(100) + " points") # a number to text
print(int(9.99)) # float to int: the decimals are cut off
print(float(7))
print(int(" 15 ")) # spaces around the number are allowed43 7.0 100 points 9 7.0 15
Note that int(9.99) gives 9: converting a float to an int cuts off the decimals, it does not round. Use round(9.99) when you want 10.
Text and numbers do not mix
Python never converts text to a number, or a number to text, on its own. Adding them together is an error:
age = 21
print("Age: " + age)Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Age: " + age)
~~~~~~~~^~~~~
TypeError: can only concatenate str (not "int") to strThe fix is to convert the number with str(age), or to let print join the values with a comma, or to use an f-string, which you will learn in String Formatting.
When a conversion fails
int and float raise a ValueError when the text is not a number of the right form. int("3.5") fails because 3.5 is not a whole number, and int("ten") fails because it is not a number at all. The Try ... Except topic shows how a program can handle this gracefully, for example by asking again.
Booleans
bool converts a value to True or False. Zero, empty text, empty lists and None become False; everything else becomes True:
print(bool(0), bool(5), bool(""), bool("no"), bool([]), bool(None))False True False True False False
Practice exercises
- Convert the strings
"12"and"30"to numbers and print their sum and their product. - Print
int(7.9),round(7.9)andfloat(int(7.9))and explain each result. - Fix the error example above in three different ways.
- Try
int("3.5")and thenint(float("3.5")). Why does the second one work?