Menu

Logical Operators

Logical Operators in Python

A logical operator joins or reverses conditions. In Python the three logical operators are written as and, or and not, all in lower case.

Upper case and lower case

Written out in an algorithm, the operators appear as AND, OR and NOT. Python keywords are case-sensitive, so AND is not the same as and: typing the upper-case spelling stops the program with a syntax error rather than combining your conditions.

In an algorithmIn Python 3
ANDand
ORor
NOTnot

Boolean results

Every condition is a Boolean expression: Python evaluates it to either True or False. These are the two Boolean values, and they always begin with capital letters. A comparison such as height >= 140 is a Boolean expression. Equality uses two equals signs: score == 10 compares two values, while score = 10 assigns a value to a variable.

The operands of and, or and not can be comparisons or Boolean variables. If has_wristband and is_member already hold True or False, then has_wristband and is_member is a Boolean expression too. not reverses a single operand, so not is_member is True when is_member is False.

The result can be stored in a Boolean variable, or used directly as a condition. In the example, can_climb stores the combined result, and not can_climb is the condition the if tests.

height = 152
has_wristband = True
is_member = False

is_tall_enough = height >= 140
can_climb = is_member or (has_wristband and is_tall_enough)
print("Climb allowed: " + str(can_climb))

if not can_climb:
    print("Ask an instructor")

Output:

Climb allowed: True

Practise this