Conditional statements and logical operators in programming
Conditional statements in programming let a program choose what to do. An if statement checks a condition, which is an expression that is either true or false, and runs a block of code only when it is true. Logical operators (AND, OR and NOT) combine simple conditions into bigger ones, such as "the user is logged in AND the basket is not empty".
Exam boards call this selection. It is one of the three ways to build any program, with sequence and iteration (loops), and the AQA GCSE specification lists relational operators and the Boolean operations NOT, AND and OR as things you must be able to use in your own programs.
If, elif and else
Here is an if statement in Python. It prices a cinema ticket by age.
age = 15
if age < 12:
price = 5
elif age < 18:
price = 7
else:
price = 10
print(price) # 7- if checks the first condition. If it is true, its block runs and the rest is skipped.
- elif (else if) is only checked when everything above it was false. You can have as many as you need.
- else catches everything left over. It has no condition and is optional.
The conditions are checked from the top down and only the first true one runs. That is why the second line can say age < 18 rather than age >= 12 and age < 18: any age under 12 was already caught. Swap the first two branches and a child of 8 would pay 7, because 8 < 18 is true and that branch now comes first.
The same in JavaScript
JavaScript writes else if in full and wraps each condition in brackets and each block in curly braces. Paste this into the Code Editor and try other ages.
function ticketPrice(age) {
if (age < 12) {
return 5;
} else if (age < 18) {
return 7;
} else {
return 10;
}
}
console.log(ticketPrice(8), ticketPrice(15), ticketPrice(40)); // 5 7 10Comparison operators
Most conditions compare two values. These comparison (or relational) operators always give true or false.
| Meaning | Python | JavaScript | Example that is true |
|---|---|---|---|
| Equal to | == | === | 3 == 3 |
| Not equal to | != | !== | 3 != 4 |
| Less than | < | < | 2 < 5 |
| Greater than | > | > | 5 > 2 |
| Less than or equal to | <= | <= | 5 <= 5 |
| Greater than or equal to | >= | >= | 6 >= 5 |
Logical operators: AND, OR and NOT
Logical operators, also called Boolean operators, join conditions together. Python spells them and, or and not; JavaScript uses &&, || and !.
- AND is true only when both sides are true.
- OR is true when at least one side is true.
- NOT flips true to false and false to true.
| A | B | A AND B | A OR B | NOT A |
|---|---|---|---|---|
| False | False | False | False | True |
| False | True | False | True | True |
| True | False | False | True | False |
| True | True | True | True | False |
These are the same rules as AND, OR and NOT logic gates in a circuit, with 1 for true and 0 for false. Fill in the missing outputs of a gate's truth table, then press Mark to check them in the course. The gate may also be NAND, which is NOT AND, or XOR, which is true when exactly one input is true.
Fill in the blank output cells of a gate's truth table.
Press Mark to have your answer marked in the Circuits course.
Combining conditions
day = 31
if day >= 1 and day <= 31:
print("Valid day")
raining = True
has_coat = False
if raining and not has_coat:
print("Take an umbrella")The first check is a range check, a common kind of validation. Python also lets you chain it as 1 <= day <= 31. When you mix operators, NOT is applied first, then AND, then OR, so add brackets whenever there is any doubt: (a or b) and c is not the same as a or (b and c).
Short-circuit evaluation
Python and JavaScript stop working out a condition as soon as the answer is certain. With AND, if the left side is false, the right side is never checked; with OR, if the left side is true, the right side is skipped. You can use this to guard against errors:
if count != 0 and total / count > 10:
print("High average")If count is 0, the division never runs, so there is no division by zero error.
De Morgan's laws
Two rules let you move a NOT inside brackets: NOT (A AND B) is the same as (NOT A) OR (NOT B), and NOT (A OR B) is the same as (NOT A) AND (NOT B). So "not (sunny and warm)" means "not sunny, or not warm". They are useful for simplifying conditions and appear in A-level Boolean algebra.
Nested if statements
An if statement can sit inside another. The inner one is only reached when the outer condition is true.
if logged_in:
if basket_items > 0:
print("Go to checkout")
else:
print("Your basket is empty")
else:
print("Please log in")Nesting is clear for two levels. Deeper than that, an and or a chain of elif branches is usually easier to read.
Switch, match and the ternary operator
When one value is compared against a list of options, many languages offer a shortcut. JavaScript, Java and C have switch. Python had nothing like it until version 3.10 added the match statement:
match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown command")The case _ line catches anything not matched above, like else. For a simple choice between two values there is also a one-line form, called the ternary or conditional expression: label = "even" if n % 2 == 0 else "odd" in Python, or n % 2 === 0 ? "even" : "odd" in JavaScript.
Common mistakes
- Writing
if x == 1 or 2. Python reads this as(x == 1) or 2, and 2 counts as true, so it is always true. Writex == 1 or x == 2, orx in (1, 2). - Using = instead of == in a condition.
- Putting branches in the wrong order. Only the first true branch runs, so put the narrowest condition first.
- Mixing up AND and OR in range checks. A value inside a range needs AND; outside a range needs OR, as in
day < 1 or day > 31. - Wrong indentation in Python. The indentation decides which lines belong to each branch.
Common questions
What is a conditional statement in programming?
What are the three logical operators?
What is the difference between if and elif?
Does Python have a switch statement?
What is a nested if statement?
What is short-circuit evaluation?
Revision cards
Say the answer first, then flip the card to check it.
Where to go next
- Solve it
Code Editor
Write and run code right in your browser
Open the tool - Learn it
Circuits
Resistors, capacitors and logic gates: build and understand real circuits
Start the course - Test it
GCSE Computer Science
A new exam-style paper every day, with instant marking and a mark scheme
Start today's paper