PythonMastery

Type conversion in Python

Convert between types with int(), float(), str() and bool(), and see which conversions fail, such as int('3.5'), and how to handle them.

Type conversion means making a value of one type from a value of another type, for example the number 42 from the text "42". Python does this when you call the type's name as a function: int(), float(), str() or bool().

The program

python
print(int("42") + 1)
print(float("3.5") * 2)
print(str(7) + " days")

print(int(9.99))
print(int(-9.99))
print(float(5))

print(bool(0), bool(3), bool(""), bool("no"))
output
43
7.0
7 days
9
-9
5.0
False True False True

How it works

What fails

int() accepts only text that looks like a whole number. Spaces at the start and end are allowed, but a decimal point, a comma or a word is not:

python
for text in ["42", " 42 ", "3.5", "4,000", "seven"]:
    try:
        print(repr(text), "->", int(text))
    except ValueError as error:
        print(repr(text), "-> ValueError:", error)
output
'42' -> 42
' 42 ' -> 42
'3.5' -> ValueError: invalid literal for int() with base 10: '3.5'
'4,000' -> ValueError: invalid literal for int() with base 10: '4,000'
'seven' -> ValueError: invalid literal for int() with base 10: 'seven'

To get a whole number from "3.5", convert in two steps, and remove the comma from "4,000" first:

python
print(int(float("3.5")))
print(int("4,000".replace(",", "")))
output
3
4000

int(float(...)) cuts off the decimal part. Use round(float(text)) if you want the nearest whole number instead. Other failing conversions: float("abc") raises ValueError, and int(None) raises TypeError. The ValueError page shows how to keep asking until the user types a valid number.

Learn the idea: Variables & Data Types, Numbers in Depth: Integers, Floats, and the math Module