10.2. Logical operators#

Logical conditions can be connected using logical operators given in Table 3.2.

Table 10.2 Logical operators#

Operator

Description

Python syntax

\(x \lor y\)

logical or

x || y

\(x \land y\)

logical and

x && y

\(\lnot x\)

logical not

~ x

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