Menu

Casting

Boolean Conversion

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.

Values that become False

These values convert to False:

  • the number zero, 0 or 0.0
  • the empty string, ''
  • an empty collection, such as an empty list
  • None, which means no value at all

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

Strings need careful checking

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.

Valuebool(value)Reason
0Falsezero counts as empty
14Truenot zero
''Falseno characters
'False'Truefive characters, so not empty
' 'Trueone space character
NoneFalseno 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 character

Output:

False
True
False
True
True

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

Practise this