Data types · 4 / 29 Theory

Type conversion

Sometimes you need to turn a value of one type into another, for example to do arithmetic with a number that the user typed. This is called type conversion (or *casting*). In Python it is done with the functions that have the same name as the types.

Explicit conversion

FunctionWhat it doesExample
int()converts to integerint("42") → 42
float()converts to decimal numberfloat("3.5") → 3.5
str()converts to textstr(10) → "10"
bool()converts to booleanbool(0) → False
list()converts to listlist("abc") → ['a', 'b', 'c']
age_text = "25"
age = int(age_text)
print(age + 1)        # 26

print(int(7.9))       # 7 (the decimal part is removed)
print(float(3))       # 3.0
print(str(3.5) + "!") # 3.5!

Conversion of the user's input

input() always returns a string, so you have to convert it when you need a number:

x = int(input("Enter a number: "))
y = float(input("Enter a decimal: "))
print(x * y)

Conversions that fail

If the value cannot be converted, Python raises a ValueError:

int("hello")      # ValueError: invalid literal for int()
int("3.5")        # ValueError: use float() first

You can handle this error with try and except, as you will see in the lesson about exceptions.

Implicit conversion

When you mix numeric types in an operation, Python converts automatically to the wider one:

print(2 + 3.5)         # 5.5 (int + float = float)
print(True + 1)        # 2   (True is 1)

But it never converts text and numbers on its own:

# print("2" + 3)       # TypeError
print("2" + str(3))    # 23
print(int("2") + 3)    # 5

Truthy and falsy values

bool() converts any value into True or False. These values are considered false: 0, 0.0, "" (empty text), [], {}, (), set() and None. Everything else is true.