Logical Operators
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.
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.
Edexcel GCSE Computer Science ยท Logical Operators