Converting Types
Sometimes a value has the wrong type for what you want to do. For example, "12" looks like a number, but it is text. A conversion function makes a new value of another type. The common ones are int, float, and str.
left = "12"
right = "4"
print(left + right)
print(int(left) + int(right))
print(float("2.5") + 1)
print(int(2.9))
Output:
124
16
3.5
2
The first print joins the two strings, so you get 124. The second converts both strings to integers first, so + adds them and gives 16. float turns the text "2.5" into a decimal number, so you can add 1 to it. int(2.9) cuts off the part after the decimal point and gives 2. It does not round.
str works the other way. str(5) turns the number 5 into the text "5".
A conversion can fail. int("abc") stops the program with a ValueError, because the text is not a whole number. Later in the course, you will learn how to handle errors like this one.
Convert the text values to numbers in the exercise.