CodeMIRAI
0 XP

Type conversion

2 min read 5 runnable examples Quiz included

Sometimes you have a value of one type and need another, such as text from the keyboard that should be a number. Converting a value is called type conversion (or casting).

The conversion functions

FunctionConverts toExampleResult
int()integerint("42")42
float()floatfloat("3.5")3.5
str()stringstr(99)"99"
bool()booleanbool(0)False
Python
age_text = "21"
age = int(age_text)
print(age + 1)

price = float("19.99")
print(price * 2)

label = "Score: " + str(87)
print(label)

int() cuts off, it doesn't round

Converting a float to an int drops everything after the decimal point:

Python
print(int(3.99))
print(int(-3.99))
print(round(3.99))   # use round() if you want the nearest whole number

Conversions that fail

If the text does not look like a number, Python raises a ValueError:

Python
print(int("twelve"))

Also note that int("3.5") fails: int() only accepts whole-number text. Use int(float("3.5")) if you need it.

What counts as True or False

bool() follows a simple rule: empty or zero is False, everything else is True.

Python
print(bool(0), bool(0.0), bool(""), bool([]), bool(None))
print(bool(1), bool(-5), bool("hi"), bool([0]), bool(" "))

Yes, bool(" ") is True: a string containing a space is not empty.

Automatic conversion

Python converts automatically in a few safe cases. Mixing an int and a float in arithmetic gives a float:

Python
print(5 + 2.0)
print(type(5 + 2.0))

But it never silently turns text into numbers or numbers into text; that is why "Age: " + 21 is an error rather than a guess.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.