Menu

Casting

bool() Conversions

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.

Text values

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.

ExpressionResultWhy
bool("x")TrueThe string has a character
bool("off")TrueThe string is not empty, even though it means off
bool("")FalseThe string is empty

bool() counts characters, so it cannot tell that "off" means not on.

Number values

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 False
  • bool(-4) gives True
  • bool(0.0) gives False
  • bool(2.5) gives True

Getting a Boolean from text

Because 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.

Practise this