Turn a value into another type with int(), float(), str() and bool().
# string to int
int("42")
# ans: 42
int("100")
# ans: 100
# float to int (truncates)
int(3.14)
# ans: 3
int(9.99)
# ans: 9
# string to float
float("3.14")
# ans: 3.14
# int to float
float(42)
# ans: 42.0
float(0)
# ans: 0.0
# int to string
str(42)
# ans: "42"
# float to string
str(3.14)
# ans: "3.14"
# bool to string
str(True)
# ans: "True"
# number to bool
bool(1)
# ans: True
bool(0)
# ans: False
bool(-5)
# ans: True
# string to bool
bool("")
# ans: False
bool("text")
# ans: True
# list to bool
bool([])
# ans: False
bool([1, 2])
# ans: True
# None to bool
bool(None)
# ans: False
Zero, empty things and None are False; everything else is True.
Predict what comes out of the converter, then press →.
# what is the result?
int("100")
# ans: 100
# what happens?
int("3.14")
# ans: ValueError
# float from string?
float("3.14")
# ans: 3.14
# bool from number?
bool(0)
# ans: False
bool(1)
# ans: True
bool(-1)
# ans: True
# bool from string?
bool("")
# ans: False
bool("False")
# ans: True (any non-empty string is True)
# string from bool?
str(True)
# ans: "True"
# int from bool?
int(False)
# ans: 0
int(True)
# ans: 1
# what about this?
int(" 42 ")
# ans: 42 (whitespace is stripped)
# edge case?
int("0b101", 2)
# ans: 5 (binary to int)
# what happens?
float("inf")
# ans: inf (infinity)
# string to int base?
int("FF", 16)
# ans: 255 (hex to int)
# float to int?
int(3.9)
# ans: 3 (truncates, doesn't round)
# bool from empty?
bool({})
# ans: False
int() truncatesIt drops the decimal part: int(9.99) is 9, not 10.
int("3.14") is a ValueError; use float() first.
0, "", [], {} and None become False; the rest become True.
int(text, base) reads binary (2) or hex (16).