3.2. Logical operators#
There are three main logical operators (also known as logical connectors) available in Python. These are used to combine conditional statements to form a logical argument.
logical OR is denoted by \(x \lor y\) and returns a true result if either \(x\) or \(y\) is true
logical AND is denoted by \(x \land y\) and returns a true result only if both \(x\) and \(y\) is true
logical NOT is denoted by \(\lnot x\) and returns the opposite values to \(x\).
We can illustrate all of the possible combinations of \(x\) and \(y\) and the logical operations given above in a truth table as shown below where 1 denotes true and 0 denotes false.
\(x\) |
\(y\) |
\(x \lor y\) |
\(x \land y\) |
\(\lnot x\) |
\(\lnot y\) |
---|---|---|---|---|---|
0 |
0 |
0 |
0 |
1 |
1 |
0 |
1 |
1 |
0 |
1 |
0 |
1 |
0 |
1 |
0 |
0 |
1 |
1 |
1 |
1 |
1 |
0 |
0 |
3.2.1. Python logical operators#
Logical conditions can be connected using logical operators given in Table 3.2.
Operator |
Description |
Python syntax |
---|---|---|
\(x \lor y\) |
logical or |
|
\(x \land y\) |
logical and |
|
\(\lnot x\) |
logical not |
|
Lets produce the truth table shown above for the these logical operators. Enter the following code into your program.
# Logical operators
print("\n x | y | x or y | x and y | not x | not y")
print("-----------------------------------------")
x, y = 0, 0
print(f" {x} | {y} | {x or y} | {x and y} | {not x:d} | {not y:d}")
x, y = 0, 1
print(f" {x} | {y} | {x or y} | {x and y} | {not x:d} | {not y:d}")
x, y = 1, 0
print(f" {x} | {y} | {x or y} | {x and y} | {not x:d} | {not y:d}")
x, y = 1, 1
print(f" {x} | {y} | {x or y} | {x and y} | {not x:d} | {not y:d}")
Run your program and your should see the following added to the console output.
x | y | x or y | x and y | not x | not y
-----------------------------------------
0 | 0 | 0 | 0 | 1 | 1
0 | 1 | 1 | 0 | 1 | 0
1 | 0 | 1 | 0 | 0 | 1
1 | 1 | 1 | 1 | 0 | 0