Lesson 8 of 30 · Working With Data
Type Conversion
Convert between strings and numbers in Python with int(), float() and str(). Fix the classic input() bug and learn what happens when a conversion fails.
- 7 min read
- Beginner
- Reviewed
- How to turn text into numbers with int() and float()
- How to turn numbers into text with str()
- What happens when a conversion is impossible
The problem
In the last lesson, input() gave you the text "25" when you wanted the number 25. Changing a value from one type to another is called type conversion, or casting.
Python has a function for each type.
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Whole number | int("25") | 25 |
float() | Decimal number | float("3.5") | 3.5 |
str() | Text | str(25) | "25" |
From text to numbers
text = "25" number = int(text) print(text + text) print(number + number) print(type(number))
The first line of output is 2525 because text is a string. The second is 50 because number is an integer.
Use float() when the number may have a decimal point.
price = float("19.99")
print(price * 2)Fixing the input() bug
Now you can do maths with what the user types. Wrap input() in int().
age = int(input("How old are you? "))
print(f"Next year you will be {age + 1}.")Python works from the inside out: input() returns "25", then int() turns it into 25, and that is what gets stored in age.
From numbers to text
str() goes the other way. You need it when joining a number to a string with +.
score = 95
print("Your score is " + str(score))
print(f"Your score is {score}")Both lines print the same thing. The f-string converts the number for you, which is one reason f-strings are usually the better choice.
Converting between int and float
print(float(7)) print(int(7.9)) print(round(7.9))
When conversion fails
Python can only convert text that looks like a number. Run this to see what happens when it does not.
number = int("hello")You get ValueError: invalid literal for int() with base 10: 'hello'. In plain English: "I cannot turn this text into a whole number".
Two cases catch beginners out:
int("3.5") # ValueError: text with a decimal point is not a whole number
int("12 kg") # ValueError: extra characters are not allowedFor the first, use float("3.5"). Spaces at the ends are fine: int(" 42 ") gives 42.
Converting to a boolean
bool() turns a value into True or False. The rule is short: empty or zero is False, everything else is True.
print(bool(0))
print(bool(42))
print(bool(""))
print(bool("hello"))This ticket calculator crashes because it tries to multiply two strings. Convert both inputs to integers so the program prints Total: 60.
price = input("Price of one ticket: ")
count = input("How many tickets? ")
# The total is wrong because both values are strings.
# Convert them so the last line of output is exactly: Total: 60
total = price * count
print(f"Total: {total}")What does int(9.99) return?
Summary
int(),float()andstr()convert values between types.- Use
int(input(...))orfloat(input(...))to read numbers from the user. int()cuts off decimals. It does not round.- Converting text that is not a number raises a
ValueError.
You have finished the module on working with data. Next, your programs learn to make decisions.
Finished reading? Tick it off to track your progress.