Skip to content
FollowtheDamnCode

Type Conversion

Turning text into numbers and numbers into text.

3 minute read

Big idea

Type conversion turns a value of one type into another: int("42") makes the number 42 from the text "42".

The converters

Each type's name is also a function that converts to that type:

  • int(x) — to a whole number
  • float(x) — to a decimal number
  • str(x) — to text
  • bool(x) — to True/False
Converting back and forth
print(int("42") + 1)
print(float("2.5") * 2)
print(str(99) + " bottles")
print(int(7.9))
output
43
5.0
99 bottles
7

Run and edit it in the app.

Notice int(7.9) is 7, not 8. int() chops off the decimal part; it doesn't round. Use round(7.9) to round.

Why you need it

Text that looks like a number is still text. This is the most common beginner surprise in Python:

Predict: what does this print?
a = "10"
b = "5"
print(a + b)
print(int(a) + int(b))
What does it print? Show the answer
105
15

Run and edit it in the app.

Watch it

When conversion fails

Python can only convert text that really is a number:

int("12")      # 12
int(" 12 ")    # 12 — spaces around it are fine
int("12.5")    # ✗ ValueError — not a whole number
int("twelve")  # ✗ ValueError
float("12.5")  # 12.5

A ValueError stops the program. In the Errors module you'll learn to catch it and ask again.

Fix the bug: the total should be 30
price = "12"
tax = "18"
print(price + tax)
output
30

Run and edit it in the app.

Implicit conversion

Python converts for you in one safe case: mixing int and float in maths gives a float:

print(3 + 0.5)   # 3.5

It never silently turns text into numbers — that would hide bugs.

What does int(9.99) give?

Think of it like

Currency exchange. You can swap dollars for euros, but you can't exchange a photo of a banknote — and Python won't exchange "twelve" for 12.

Key terms

  • Type conversion (casting) — Making a value of one type from another.
  • ValueError — The error when text can't be converted, like int("abc").
  • Truncate — Cut off the decimal part.

Check yourself

What does int("8") + 2 give?

What does int("3.7") do?

What does str(42) give?