BasicsChapter 11 of 114
Casting
Converting between types on purpose, and where conversion fails.
Converting on purpose
Python will not quietly turn a string into a number for you. You ask, using the type's own name as a function:
print(int("42") + 1)
print(float("3.5") * 2)
print(str(99) + " bottles")Output
43 7.0 99 bottles
Why you need it
Anything typed by a person arrives as text, even when it looks like a number:
answer = "10"
print(answer * 3)
print(int(answer) * 3)Output
101010 30
Multiplying a string repeats it. That is a real feature, and it is also the classic bug when you forgot to convert.
int() truncates
Going from float to int throws the fraction away. It does not round:
print(int(3.9))
print(int(-3.9))
print(round(3.9))Output
3 -3 4
When conversion fails
int() accepts a string only if the whole thing is a number. Anything else raises ValueError:
print(int("42"))
print(int(" 42 "))Output
42 42
Surrounding whitespace is fine. A decimal point is not — int("3.5") fails, so convert in two steps:
print(int(float("3.5")))Output
3
Handling bad input
Since failure is an exception, wrap the conversion when the value comes from outside your program:
for text in ["12", "twelve"]:
try:
print("got", int(text))
except ValueError:
print(text, "is not a number")Output
got 12 twelve is not a number
Converting to bool
bool() follows the truthiness rules: empty and zero are False, everything else is True.
print(bool(0), bool(1), bool(-1))
print(bool(""), bool("hi"), bool("False"))
print(bool([]), bool([0]))Output
False True True False True True False True
Other bases
int() takes a second argument saying what base the text is written in:
print(int("ff", 16))
print(int("1010", 2))Output
255 10
Test yourself
3 questionsWhat does "10" * 3 give?
Show the answer
"101010" — Multiplying a string repeats it. Convert with int() first when you meant arithmetic.
What does int("3.5") do?
Show the answer
Raises ValueError — int() only accepts text that is a whole number. Go through float first: int(float("3.5")).
What is bool("False")?
Show the answer
True — It is a non-empty string, so it is truthy. The letters inside mean nothing to bool().
Booleans
True, False, and the rule that decides whether any value counts as either.