Logical expressions

Logical expressions#

(Click here for the German version of this page)

The data type boolean#

Now the topic is logical expressions.

Python has the data type Boolean, which can have one of the two values true and false.

True und False are the respective Python keywords. Both have the first letter capitalized and all other letters in lowercase.

Correct:
x = True
y = False

Incorrect:
x = true
y = false
x = TRUE
y = FALSE
x = tRuE
y = fAlSe

When using an Editor with Python syntax highlighting or autocompletion, one can make sure to write it correctly.

Logical expressions#

The comparison operator, which checks for equality, is == just like in almost all other programming languages. Inequality is checked using the operator !=.

x = 5
y = 5

print(x == y)
# --> True

print(x != y)
# --> False

To check whether a variable has a null value, one can use the above comparison operator or the keyword is.

x = None

print(x == None)
# --> True

print(x != None)
# --> False

print(x is None)
# --> True

print(x is not None)
# --> False

# Alternatively:
print(not x is None)
# --> False

Comparisons of concrete values are also possible with >,<,>=,<=.

To negate a Boolean expression, C used an exclamation mark.

int x = 5;
int y = 5;

printf("%d", !(x == y));
// 0 i.e., False

Python instead uses the keyword not The above example in Python would be:

x = 5
y = 5

print(not(x == y))
# --> False

The same approach is used for the “logical and” and “logical or”.

The respective keywords are and and or.

C:

int x = 1; // i.e., True
int y = 0; // i.e., False
int z = 1; // i.e., True

printf("%d", x && z);
// --> 1 i.e., True

printf("%d", x && y);
// --> 0 i.e., False

printf("%d", x || y);
// --> 1 i.e., True

Python: Python:

x = True
y = False
z = True

print(x and z)
# --> True

print(x and y)
# --> False

print(x or y)
# --> True

Exercise#

You are given the following logical expression. Your task is to translate it into Python code. So you can properly execute the code, please use the concrete values \(x=5\), \(y=5\), \(z=3\), \(t=True\) and \(f=False\). Using those conrete values results in tautologies. No simplifications must be performed.

\(expression = \)

\((x=y \land ((x=z \lor \neg(y < z)) \lor\)

\(\neg((\neg t \lor f) \land (t \land \neg (x < z)))))\)

Alternatively if you do not want to use the above expression, you are also free to use the following C code. The C code and the expression above are equivalent.

# Here you can try to solve this problem...
# Replace ... with your code.
x = 5
y = 5
z = 3
t = True
f = False

print(
    ...
)
Ellipsis