Logical Operators
A logical expression is a condition built from two or more comparisons joined with and or or, or a single comparison reversed with not. It works out to a single True or False, so it can go straight into the condition of an if, elif or while statement. Nothing extra is needed around it: the expression is the condition.
Imagine a climbing wall that accepts you only if you are at least 12 and you have handed in a consent form. One way is a second if inside the first, asking about the form. Joining both comparisons with and does the same job in one condition, which is shorter and less likely to go wrong. The elif line below repeats the idea: its expression is tested only when the first condition was False.
age = int(input("Age: "))
consent = input("Consent form handed in? yes or no: ")
if age >= 12 and consent == "yes":
print("You can climb")
elif age >= 12 and consent != "yes":
print("Hand in your consent form first")
else:
print("Sorry, you are too young")Output when the user types 12, yes:
Age: 12
Consent form handed in? yes or no: yes
You can climb
An or expression is True when at least one comparison is True, so it suits a decision where either event is enough. This game ends when the score reaches 100 or the player has no lives left.
score = int(input("Score: "))
lives = int(input("Lives left: "))
if score >= 100 or lives == 0:
print("Game over")
else:
print("Keep playing")Output when the user types 120, 2:
Score: 120
Lives left: 2
Game over
A condition finishes at the colon, and the indented lines below it run when the condition is True. Indenting a line that should sit outside the decision makes the computer treat it as part of the decision, and leaving out indentation where it is needed causes an error. Correct logic can still misbehave if a statement lands in the wrong block.
A while loop tests its condition before each repeat, so a logical expression there decides whether the loop runs again. A practice game might repeat while the timer is above zero and the goals scored is below five: the loop stops as soon as either part becomes False, so it ends when time runs out or the target is reached. Swap in or and it carries on while at least one part is True, stopping only when both are False. A not reverses a test, so a loop can keep running until that event happens.
| Loop condition | Repeats while | Stops when |
|---|---|---|
timer is above 0 and goals is below 5 | both comparisons are True | either comparison becomes False |
timer is above 0 or goals is below 5 | at least one comparison is True | both comparisons are False |
Edexcel GCSE Computer Science · Logical Operators