Casting
Boolean conversion uses the bool() function to turn a value into either True or False. Python checks whether the value counts as empty or zero, not what the value looks like.
These values convert to False:
0 or 0.0''None, which means no value at allEvery other value converts to True, including negative numbers such as -6, real numbers such as 0.5, and any collection holding at least one item.
A string converts to True when it holds at least one character. Python never reads the word and decides what it means; it only checks whether the string is empty. So 'False', '0', 'no' and even a single space ' ' all convert to True. The empty string '' is the only string that converts to False.
| Value | bool(value) | Reason |
|---|---|---|
0 | False | zero counts as empty |
14 | True | not zero |
'' | False | no characters |
'False' | True | five characters, so not empty |
' ' | True | one space character |
None | False | no value |
print(bool(0)) # zero
print(bool(14)) # a non-zero number
print(bool('')) # empty string
print(bool('False')) # non-empty string
print(bool(' ')) # one space characterOutput:
False
True
False
True
TrueThe program shows the same rule at work. Zero counts as empty, so it converts to False, while a non-zero number is True. The string 'False' is judged on its five characters alone, so it converts to True even though the word looks like a false value.
Edexcel GCSE Computer Science · Casting