Menu

Logical Operators

Readable Logical Expressions

A compound condition combines more than one comparison, joining them with and or or, or reversing one with not. You work out each test and the operator beside it together, so the way you lay the condition out decides whether another programmer, or you next week, can see the intended logic straight away.

Lay the condition out so the logic shows

  • Put a space either side of every operator and every comparison, so the parts do not blur into one long string of symbols.
  • Put brackets around each group that belongs together, especially when and and or are mixed, so it is obvious which tests must all pass and which are alternatives.
  • Keep the keywords in lower case. Python is case-sensitive, so And is not the same word as and and the line stops with an error instead of running.
  • Keep every comparison complete on both sides of an operator. A test that has lost its variable half way along cannot be worked out.

Shorter, but only while it stays clear

Logical operators let one condition replace a stack of nested if statements, which makes a program shorter and easier to follow. That only works while the condition stays readable. A long condition with several and and or parts crammed onto one line hides the grouping, so the reader has to work out the order in their head. It still runs, but it is much easier to end up with a logic error โ€” a test that is written wrongly and so checks the wrong thing. Bracketing the groups, or splitting the logic into two shorter conditions, keeps the meaning in plain sight.

# Cinema discount: a teenager with enough card points
age = int(input("Enter your age: "))
points = int(input("Enter your card points: "))

if (age >= 13) and (age <= 19) and (points > 50):
    print("Half price ticket")
else:
    print("Full price ticket")

Output when the user types 15, 80:

Enter your age: 15
Enter your card points: 80
Half price ticket

Every part of the condition above is bracketed and spaced out, so you can see at once that all three tests have to be true together for the discount to apply.

Practise this