Type conversion
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
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | integer | int("42") | 42 |
float() | float | float("3.5") | 3.5 |
str() | string | str(99) | "99" |
bool() | boolean | bool(0) | False |
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:
print(int(3.99))
print(int(-3.99))
print(round(3.99)) # use round() if you want the nearest whole numberConversions that fail
If the text does not look like a number, Python raises a ValueError:
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.
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:
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.