10.2. 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 a truth table for the these logical operators. Enter the following code into your program.
% Logical Operators
fprintf(" x | y | x or y | x and y | not x | not y \n")
fprintf("------------------------------------------ \n")
x = 0;
y = 0;
fprintf(" %d | %d | %d | %d | %d | %d\n", x, y, x || y, x && y, ~x, ~y)
x = 0;
y = 1;
fprintf(" %d | %d | %d | %d | %d | %d\n", x, y, x || y, x && y, ~x, ~y)
x = 1;
y = 0;
fprintf(" %d | %d | %d | %d | %d | %d\n", x, y, x || y, x && y, ~x, ~y)
x = 1;
y = 1;
fprintf(" %d | %d | %d | %d | %d | %d\n", x, y, x || y, x && y, ~x, ~y)
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