Casting
bool() is a casting function that turns a value into a Boolean, so the result is either True or False. It does not read the meaning of a value; it only checks whether the value is empty or zero.
Any string with at least one character gives True, even if the characters spell a word that means false. Only the empty string gives False.
| Expression | Result | Why |
|---|---|---|
bool("x") | True | The string has a character |
bool("off") | True | The string is not empty, even though it means off |
bool("") | False | The string is empty |
bool() counts characters, so it cannot tell that "off" means not on.
Zero is the only number that gives False. Every other number gives True, whether it is positive or negative, whole or real.
bool(0) gives Falsebool(-4) gives Truebool(0.0) gives Falsebool(2.5) gives TrueBecause bool() only checks whether text is empty, it cannot turn a label into False. Instead, compare the text with the wording you have decided means true: if the text matches, the comparison gives True, and if it does not, the comparison gives False.
switchSetting = "off"
lightsOn = switchSetting == "on" # comparison gives a Boolean
print(lightsOn)
print(bool(switchSetting))
print(bool(""))
print(bool(0))Output:
False
True
False
False
The comparison tests what the text means, so a setting of "off" is treated as not on. The bool() calls show the rule the other way round: any text at all counts as true, whatever it says.
OCR GCSE Computer Science · Casting