8. The Boolean type¶
The Boolean data type is used to represent two values: True and False. These Boolean values are essential in programming, as they are used to make decisions and control the flow of a program.
The word True represents the true value, while the word False represents the false value. Both words must be written with the first letter capitalized and the rest lowercase, since Python is case sensitive (it is Case Sensitive).
Boolean values are the result of comparison operations or logical evaluations. For example, if we want to compare if two variables are equal, we can use the equality operator "==". If the comparison is true, the result will be True; otherwise it will be False.
comparison operators¶
These operators are used to compare two values. The result will always be a boolean value, True or False.
Operator | Name | Description |
---|---|---|
== | Equal | True if the operand on the left is the same as the operand on the right. False otherwise. |
!= | Distinct | True if the operand on the left is different from the operand on the right. False otherwise. |
> | Greater than | True if the left operand is greater than the right operand. False otherwise. |
< | Smaller than | True if the operand on the left is less than the operand on the right. false otherwise. |
>= | Greater than or equal | True if the operand on the left is greater than or equal to the operand on the right. False otherwise. |
<= | less than or equal to | True if the operand on the left is less than or equal to the operand on the right. False otherwise. |
Examples:
>>> 1 == 1
True
>>> 1 == 1.0
True
>>> 'Hola' == 'Mundo'
False
>>> 5 > 8
False
>>> 10 <= 12
True
>>> 'A' < 'B'
True
Logical operators¶
Boolean operators are used to perform logical operations between Boolean values (True and False) or expressions that can evaluate to Booleans.
Operator | Description |
---|---|
a and b | If 'a' is false, return 'a'. If 'a' is true, return 'b'. It is only true if 'a' and 'b' are both true. |
a or b | If 'a' is false, return 'a'. If 'a' is true, return 'b'. It is true if either 'a' or 'b' are true. |
note | If 'a' is false, return true. If 'a' is true, return false (False). |
bool(a) | If 'a' is zero or empty, return false. Otherwise, it returns true (True) |
Examples:
>>> True and False
False
>>> False and True
False
>>> True and True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
>>> bool(0)
False
>>> bool(1)
True
>>> bool(7)
True
>>> bool(-1)
True