Lesson 5 of 10
Sometimes a value is the wrong type for what you need — you have a number stored as text, or you need to combine a number with a string. Python lets you convert between types explicitly.
str() — convert to text
age = 25
message = "I am " + str(age) + " years old"
print(message)
Without str(age), this line would crash — Python won't automatically combine a str and an
int with +. Converting age to a string first fixes that.
int() — convert to a whole number
text_number = "42"
real_number = int(text_number)
print(real_number + 8)
int() also truncates (chops off, doesn't round) decimals when converting from a float:
print(int(9.9))
print(int(9.1))
float() — convert to a decimal number
text_price = "19.99"
price = float(text_price)
print(price * 2)
When conversion fails
Not every string can become a number. This will raise an error:
int("hello")
You'll see errors like this throughout your Python career — reading them (they usually tell you exactly what went wrong) is a core skill. We'll cover handling errors properly in Module 6.
Try it yourself
You're given a number as text. Convert it to an int, add 10 to it, then print the result.
Checkpoint
str(x)convertsxto text.int(x)convertsxto a whole number (truncates floats).float(x)convertsxto a decimal number.- Converting an invalid string (like
int("hello")) raises an error.
Questions about this lesson
Log in to ask a question.