Today we’ll be talking about the boolean type in Python.
The boolean data type can have only one of two values: True or False.
We can assign a boolean value explicitly:
>>> she_is_coming = True
>>> if she_is_coming == True:
... print("Beware...")
...
Beware...
>>> winning = False
>>> if winning == False:
... print("Try harder!")
...
Try harder!
We can rewrite this code in a more concise manner. In the condition check we can write just she_is_coming, which is equivalent to she_is_coming == True:
>>> if she_is_coming:
... print("Beware...")
Accordingly, the equivalent of winning == False is not winning:
>>> if not winning:
... print("Try harder!")
Expressions can evaluate to a boolean value. They can be practically of any length and complexity:
>>> 2 + 3 == 8
False
>>> 3 > -11
True
>>> len("Hi there") < 100
True
>>> ["I", "you", "she", "they"][1] == "they"
False
>>> max([5, 16, 2]) <= len("just counting") + min((7, 0, -3, 8))
False
We can check whether an expression is of boolean type using the type function:
>>> type(2 + 2 == 4)
<class 'bool'>
The boolean values True and False may even be used as numbers. Then True equals 1 and False equals 0:
>>> 2 * True
2
>>> False + 8 - True
7
In such a case the boolean value doesn’t change the numeric type of the expression:
>>> a = False + 3
>>> type(a)
<class 'int'>
>>> b = 3.75 * True
>>> type(b)
<class 'float'>
Numbers may also be understood as boolean values. Zero is understood as False, any other number as True.
So, here we have a condition which is not met:
>>> if 0: # means as much as ‘if False’
... print(3)
...
The following two conditions are met:
>>> if 54: # means as much as ‘if True’
... print(5)
...
5
>>> if -56: # means as much as ‘if True’
... print("hi")
...
hi
Actually, there are a few objects which are evaluated as False:
– the boolean literal False
– numerical 0 values (integer 0, float 0.0, complex 0.0+0.0j)
– empty strings, lists, tuples and dictionaries
– the value None
Other objects are evaluated as True.
Here’s the video version of the article: