Why Do Programs Need to Make Decisions?
Every day you make decisions. "If it's raining, take an umbrella. Otherwise, wear sunglasses." You check a condition (is it raining?) and then choose what to do based on the answer. Programs can make decisions too — and they do it millions of times a second.
Conditional logic (also called selection) is how programs respond differently to different situations. Without it, a program would do exactly the same thing every single time, no matter what. That would be pretty useless!
Think about how many things rely on decisions in the real world:
- Traffic lights — if the timer has finished, change from green to amber to red.
- Age checks on websites — if the user is under 13, block access to the content.
- Game logic — if the player's health reaches zero, the game is over.
- Weather apps — if the temperature drops below zero, display a frost warning.
All of these use if statements — the most fundamental way a program makes choices. In your GCSE exam, this concept is called selection, and it is one of the three basic programming constructs (along with sequence and iteration).
What You Will Learn
- How to use
if,elif, andelseto control the flow of your programs - How to use comparison operators to compare values
- How to build boolean expressions that evaluate to
TrueorFalse - How to combine conditions using logical operators (
and,or,not) - How to nest if statements inside each other for more complex decisions
- How to use truth tables to reason about combined conditions
See If Statements in Action
The best way to understand if statements is to run some code and experiment with the values. Try each example below, then change the values to see different outcomes.
Example 1: A Simple If Statement
This program checks whether someone is old enough to drive. If the condition is True, the indented line runs. If it is False, the indented line is skipped entirely.
age >= 16. There are two print() statements — one indented inside the if, and one not indented. How many lines of output will there be? Will "Thanks for checking." always appear?
Thanks for checking.
Both lines print because age is 16. The second print is NOT inside the if block, so it always runs regardless of the condition.
age = 16
if age >= 16:
print("You can drive!")
print("Thanks for checking.")
age to 14 and run the code again. What happens to the first message? Why does the second message still appear?
Example 2: If / Else
Sometimes you want to do one thing when the condition is true and something else when it is false. That is where else comes in — it catches everything that does not match the if.
temperature = 25
if temperature >= 20:
print("It's warm outside!")
print("Wear a t-shirt and sunglasses.")
else:
print("It's a bit chilly.")
print("Better grab a jacket.")
temperature to 10 to see the else branch. What about 20 exactly — which branch runs and why?
Example 3: If / Elif / Else — Multiple Conditions
When there are more than two possible outcomes, use elif (short for "else if") to check additional conditions. Python works through them from top to bottom and runs the first one that is true.
75 >= 90? Is 75 >= 70? Is 75 >= 50? Which branch will run — and will Python keep checking after it finds a match?
Your grade is B
Python stops at the FIRST true condition. 75 >= 70 is True, so grade = "B". It does NOT continue to check 75 >= 50, even though that is also true.
score = 75
if score >= 90:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 50:
grade = "C"
else:
grade = "U"
print("Your score is " + str(score))
print("Your grade is " + grade)
95, 70, 55, and 30. Does each give the grade you expect? What happens if you set the score to exactly 90?
Example 4: Nested If Statements
Sometimes one decision leads to another. You might need to check a second condition only if the first one is already true. This is called nesting — placing an if statement inside another if statement. Notice how the inner if is indented further than the outer one.
age = 15
has_ticket = True
if age >= 12:
print("You are old enough for the film.")
if has_ticket:
print("Enjoy the movie!")
else:
print("You need to buy a ticket first.")
else:
print("Sorry, this film is for ages 12 and over.")
age to 10 — does Python even check the ticket? Now set age back to 15 but change has_ticket to False. Can you see how the nested structure works?
Example 5: Logical Operators in Action
Real-world programs often need to check multiple conditions at once. A login system needs the username and the password to both be correct. Here we use and to combine conditions into a single, powerful check.
# A simple login system
correct_username = "admin"
correct_password = "python123"
entered_username = "admin"
entered_password = "python123"
if entered_username == correct_username and entered_password == correct_password:
print("Login successful! Welcome back.")
elif entered_username != correct_username and entered_password != correct_password:
print("Both username and password are wrong.")
elif entered_username != correct_username:
print("Username is incorrect.")
else:
print("Password is incorrect.")
entered_username to "user" and run it. Then change only the password to "wrong". Can you get all four different messages to appear?
Example 6: String Comparisons
If statements work brilliantly with strings (text), not just numbers. You can check passwords, menu choices, and user responses. One important thing: Python is case-sensitive, so "Yes" and "yes" are different. You can use .lower() to handle this.
# A restaurant ordering system
print("=== Python Cafe ===")
print("Menu: pizza, salad, soup")
print()
choice = "Pizza"
# Convert to lowercase so "Pizza", "PIZZA", "pizza" all work
choice_lower = choice.lower()
if choice_lower == "pizza":
print("Great choice! One pizza coming up. That's £8.50.")
elif choice_lower == "salad":
print("A healthy option! One salad on the way. That's £6.00.")
elif choice_lower == "soup":
print("Perfect for today's weather! One soup. That's £4.50.")
else:
print("Sorry, we don't have '" + choice + "' on the menu.")
choice to "SALAD" or "Soup" — does it still work? What happens if you type "burger"? Try removing the .lower() call and using "Pizza" with a capital P — what goes wrong?
How If Statements Work
The Basic Idea
An if statement asks a question that has a yes or no answer. In Python, that answer is either True or False — these are called boolean values.
- If the condition is
True, the indented block of code runs. - If the condition is
False, the indented block is skipped.
# You can see boolean values directly
print(10 > 5) # True
print(3 == 7) # False
print(4 != 4) # False
print(6 <= 6) # True
Comparison Operators
These operators compare two values and return True or False. In your GCSE, these are also called relational operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 7 | True |
> | Greater than | 10 > 20 | False |
<= | Less than or equal to | 5 <= 5 | True |
>= | Greater than or equal to | 4 >= 9 | False |
Logical Operators: Combining Conditions
Sometimes one condition is not enough. You can combine conditions using and, or, and not:
and— both conditions must be true. "If it is Saturday and it is sunny, go to the park."or— at least one condition must be true. "If it is Saturday or Sunday, have a lie-in."not— flips the result. "If it is not raining, walk to school."
age = 15
has_permission = True
if age >= 13 and has_permission:
print("You can create an account.")
else:
print("Sorry, you cannot sign up yet.")
# Try changing age or has_permission to see different results
Truth Tables
A truth table shows every possible combination of inputs for a logical operator and what the result will be. These are essential for your GCSE — you need to be able to read and create them. Think of A and B as two conditions.
AND Truth Table
With and, the result is True only when both inputs are True:
| A | B | A and B |
|---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
OR Truth Table
With or, the result is True when at least one input is True:
| A | B | A or B |
|---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
NOT Truth Table
With not, the result is simply the opposite of the input:
| A | not A |
|---|---|
True | False |
False | True |
# Verify the truth tables yourself!
print("--- AND ---")
print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False
print("--- OR ---")
print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False
print("--- NOT ---")
print(not True) # False
print(not False) # True
Indentation Matters!
Unlike many other programming languages, Python uses indentation (spaces at the start of a line) to define which lines belong to an if block. Every line inside the block must be indented by the same amount — typically four spaces.
if, elif, and else line must end with a colon :. The code that belongs to that branch must be indented on the next line. If you forget either, Python will give you a syntax error.
# Correct - the indented lines belong to the if block
weather = "rainy"
if weather == "rainy":
print("Take an umbrella!")
print("Wear a waterproof coat.")
print("Have a good day!") # This always runs (not indented)
Common Misconception: = vs ==
= and ==.
=is assignment — it stores a value in a variable. Example:name = "Alice"==is comparison — it checks whether two values are equal. Example:if name == "Alice":
If you accidentally write if age = 18: instead of if age == 18:, Python will give you a SyntaxError.
# Assignment vs Comparison - run this to see the difference
favourite_colour = "blue" # = assigns the value
if favourite_colour == "blue": # == checks the value
print("Great choice! Blue it is.")
else:
print("That's a nice colour too.")
elif is short for "else if", but different languages spell it differently. JavaScript and C++ use else if (two words), Ruby uses elsif, and PHP uses elseif. They all do the same thing — but Python's version is the shortest to type!
if age > 0 and age < 18:, you can write if 0 < age < 18:. This is valid Python and means "age is between 0 and 18". Most other languages do not allow this — it is one of Python's neat tricks!
True/False values we use in programming are called booleans, named after the English mathematician George Boole (1815–1864). In 1854, Boole published The Laws of Thought, which laid the foundations for the true/false logic that powers every computer today. Every time you write an if statement, you are using Boole's algebra!
Selection in the Real World
Selection is not just a classroom concept — it is everywhere in the software you use every day:
- Login systems: If the username
andpassword both match the stored values, grant access. Otherwise, show an error. This is a classic use of theandoperator. - E-commerce: If the basket total is greater than £50, apply free delivery. Online shops use selection to calculate discounts and promotional offers.
- Games: If
player_health <= 0, trigger "game over". Games use thousands of if statements to manage health, scores, and level progression. - Smart homes: If the temperature is below 18°C
andthe time is after 6pm, turn on the heating. Smart thermostats like Nest use selection logic constantly. - Social media: If a user's age is less than 13, block account creation. This is required by law under rules like COPPA (Children's Online Privacy Protection Act).
Key Vocabulary
Make sure you understand these key terms — they will appear in your GCSE exam:
| Term | Definition |
|---|---|
| Selection | A programming construct where the program chooses which path to follow based on a condition. |
| Condition | An expression that evaluates to True or False. For example, age >= 18. |
| Boolean | A data type with only two possible values: True or False. Named after George Boole. |
| Comparison Operator | An operator that compares two values and returns a boolean. Also called a relational operator. Examples: ==, !=, <, >. |
| Relational Operator | Another name for a comparison operator. Used in the OCR and Edexcel specifications. |
| Logical Operator | An operator that combines or modifies boolean values: and, or, not. |
| if | A keyword that starts a conditional block. The code inside runs only if the condition is True. |
| elif | Short for "else if". Checks an additional condition when the previous one was False. |
| else | A catch-all block that runs when none of the preceding conditions were True. Must come last. |
| Indentation | The spaces at the start of a line that tell Python which block a line belongs to. Typically four spaces. |
| Nested Selection | An if statement placed inside another if statement. Used when a second decision depends on the first. |
| Truth Table | A table showing all possible input combinations for a logical expression and their resulting output. |
Worked Example: Building a Grade Calculator
Let us walk through a complete example step by step. We need a program that takes a student's score (0–100) and gives them a grade:
- A* — 90 and above
- A — 80 to 89
- B — 70 to 79
- C — 60 to 69
- D — 50 to 59
- U — below 50 (ungraded)
Step 1: Think about the order. We start with the highest grade and work downwards. Because Python stops at the first true condition, we only need to check the lower boundary of each grade.
Step 2: Handle invalid input. What if someone enters 105 or -3? A good program checks for this.
Step 3: Add a motivational message. We can use another if/elif/else to print encouragement based on the grade.
# Worked Example: Grade Calculator
score = 73
# Step 2: Check for invalid input first
if score < 0 or score > 100:
print("Error: Score must be between 0 and 100.")
else:
# Step 1: Determine the grade (highest boundary first)
if score >= 90:
grade = "A*"
elif score >= 80:
grade = "A"
elif score >= 70:
grade = "B"
elif score >= 60:
grade = "C"
elif score >= 50:
grade = "D"
else:
grade = "U"
print("Score: " + str(score) + "/100")
print("Grade: " + grade)
# Step 3: Motivational message
if grade == "A*" or grade == "A":
print("Outstanding work! Keep it up!")
elif grade == "B" or grade == "C":
print("Good effort. A bit more revision could push you higher!")
elif grade == "D":
print("You passed, but there is room for improvement.")
else:
print("Don't give up! Let's work on the areas you found tricky.")
95, 82, 73, 55, 40, and 105. Does every score give the correct grade? What grade does 90 get? What about 89?
Common Mistakes to Avoid
- Using
=instead of==in conditions. Remember:=assigns,==compares. Writingif score = 90:causes aSyntaxError. - Forgetting the colon
:after if/elif/else. Every condition line must end with a colon. Missing it causes aSyntaxError. - Wrong indentation (or mixing tabs and spaces). All lines inside an if block must be indented the same amount. Mixing tabs and spaces causes an
IndentationError. Stick to four spaces always. - The order of elif matters. Python runs the first true condition. If you put
score >= 50beforescore >= 90, a score of 95 would match the wrong branch. Always put the most specific conditions first. - Using
elifafterelse. Theelseblock must always be the last branch. You cannot writeelifafterelse— Python will give you aSyntaxError.
Your Turn
Now it is time to write your own if statements. Work through these exercises from easiest to hardest. Remember: the colon : at the end of each condition line, and indent the code inside each block by four spaces.
Exercise 1: Positive, Negative, or Zero?
GuidedWrite a program that checks whether a number is positive, negative, or zero, and prints an appropriate message for each case.
SET number TO a value
IF number is greater than 0 THEN
PRINT "The number is positive"
ELSE IF number is less than 0 THEN
PRINT "The number is negative"
ELSE
PRINT "The number is zero"
number = 7
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
print("The number you checked was " + str(number))
Try changing number to -3 and then to 0. Each time, predict which message will appear before you run the code. You need three branches: if for positive, elif for negative, and else for zero.
Exercise 2: Ticket Pricing System
Partially GuidedA cinema charges different prices based on age:
- Children (under 12): £5.00
- Adults (12 to 64): £10.00
- Seniors (65 and over): £7.00
The starter code below has some gaps for you to fill in.
SET age TO a value
IF age is less than 12 THEN
SET price TO 5.00, SET ticket_type TO "Child"
ELSE IF age is greater than or equal to 65 THEN
SET price TO 7.00, SET ticket_type TO "Senior"
ELSE
SET price TO 10.00, SET ticket_type TO "Adult"
PRINT ticket_type and price
age = 35
if age < 12:
price = 5.00
ticket_type = "Child"
elif age >= 65:
# Fill in the price and ticket_type for seniors
price = ...
ticket_type = ...
else:
# Fill in the price and ticket_type for adults
price = ...
ticket_type = ...
print(ticket_type + " ticket: £" + str(price) + "0")
Replace each ... with the correct value. For seniors, the price is 7.00 and the ticket type is "Senior". For adults, the price is 10.00 and the ticket type is "Adult". Test with ages 8, 35, and 70.
Exercise 3: Decision Game
Open-EndedCreate a simple text-based decision game. The player's choice should lead to different outcomes. Use variables, if/elif/else, and print statements to tell a short story.
PRINT the scene description
SET choice TO the player's selection ("red", "blue", or "green")
IF choice is "red" THEN
PRINT the red key outcome
ELSE IF choice is "blue" THEN
PRINT the blue key outcome
ELSE IF choice is "green" THEN
PRINT the green key outcome
ELSE
PRINT "Invalid choice"
print("=== The Three Keys ===")
print("You find a locked door with three keyholes.")
print("There is a red key, a blue key, and a green key.")
print()
# Change this variable to try different choices
choice = "red"
if choice == "red":
print("You use the red key...")
print("The door opens to a room full of treasure! You win!")
elif choice == "blue":
print("You use the blue key...")
print("The door opens to a library of ancient secrets.")
print("You learn a powerful spell!")
elif choice == "green":
print("You use the green key...")
print("The door opens to a beautiful garden.")
print("You find a friendly dragon who becomes your companion!")
else:
print("That key doesn't exist! Try red, blue, or green.")
This exercise is open-ended — be creative! Ideas to extend it:
- Add a second decision after the first one.
- Use
orto accept different capitalizations (e.g.,if choice == "red" or choice == "Red":). - Add a scoring system with a
pointsvariable.
Exercise 4: Login System
Partially GuidedWrite a login system that checks a username and a password. Give specific error messages:
- Both correct:
"Access granted. Welcome!" - Both wrong:
"Error: Username and password are both incorrect." - Only username wrong:
"Error: Username not recognised." - Only password wrong:
"Error: Incorrect password."
SET correct_user TO "student", SET correct_pass TO "gcse2025"
SET entered_user TO a value, SET entered_pass TO a value
IF entered_user equals correct_user AND entered_pass equals correct_pass THEN
PRINT "Access granted. Welcome!"
ELSE IF both are wrong THEN
PRINT "Error: Username and password are both incorrect."
ELSE IF entered_user is wrong THEN
PRINT "Error: Username not recognised."
ELSE
PRINT "Error: Incorrect password."
# Login System
correct_user = "student"
correct_pass = "gcse2025"
# Change these to test different combinations
entered_user = "student"
entered_pass = "gcse2025"
# Complete the if/elif/else block below
if entered_user == correct_user and entered_pass == correct_pass:
print("Access granted. Welcome!")
elif entered_user != correct_user and entered_pass != correct_pass:
# What message should go here?
print(...)
elif entered_user != correct_user:
# What message should go here?
print(...)
else:
# What message should go here?
print(...)
Replace each ... with the correct error message string. Think about what must be true for each branch:
- Second branch: both are wrong →
"Error: Username and password are both incorrect." - Third branch: only username is wrong →
"Error: Username not recognised." - Else: username is correct but password is wrong →
"Error: Incorrect password."
Test all four combinations!
Exercise 5: Adventure Game Extended
Open-EndedCreate a text adventure with at least 3 decision points, using nested if statements and at least one logical operator. The player explores a castle — they need a key and a torch to succeed, and can go left or right.
SET has_torch TO False, SET has_key TO False
PRINT "You enter a dark castle..."
SET room1_choice TO "left" or "right"
IF room1_choice is "left" THEN
PRINT "You find a torch!", SET has_torch TO True
ELSE IF room1_choice is "right" THEN
PRINT "You find a golden key!", SET has_key TO True
SET room2_choice TO "chest" or "door"
IF room2_choice is "chest" AND has_key THEN
PRINT "You unlock the chest and find treasure!"
ELSE IF room2_choice is "door" AND has_torch THEN
PRINT "You light your way through the dark passage!"
ELSE
PRINT "You don't have the right item..."
# Adventure Game - Expand this!
print("=== The Mysterious Castle ===")
print()
has_torch = False
has_key = False
# Decision 1: Which way do you go?
room1_choice = "left" # Try "left" or "right"
print("You enter the castle and reach a fork in the corridor.")
if room1_choice == "left":
print("You go left and find a dusty old torch on the wall.")
print("You take it! This could be useful.")
has_torch = True
elif room1_choice == "right":
print("You go right and discover a golden key on the ground.")
print("You pick it up! It might unlock something.")
has_key = True
else:
print("You stand still, unsure what to do...")
print()
# Decision 2: What do you interact with?
room2_choice = "chest" # Try "chest" or "door"
print("You enter a large hall. There is a locked chest and a dark doorway.")
if room2_choice == "chest" and has_key:
print("You use the golden key to unlock the chest.")
print("Inside you find a pile of gold coins! You win!")
elif room2_choice == "chest" and not has_key:
print("The chest is locked. If only you had a key...")
elif room2_choice == "door" and has_torch:
print("You light the torch and walk through the dark passage.")
print("It leads to a secret garden outside the castle! Freedom!")
elif room2_choice == "door" and not has_torch:
print("It's too dark to see anything. You trip and fall!")
else:
print("You are unsure what to do next.")
# Challenge: Add a third decision point below!
Ideas to extend the adventure:
- Add a third room with a new decision (fight a dragon or sneak past?).
- Add a
healthvariable and checkif health <= 0:for game over. - Use
andto require two items for the final challenge. - Add a scoring system and print the total at the end.
Check Your Understanding
Before moving on, think about these questions. You do not need to write code — just think through your answers.
- What is the difference between
=and==in Python? - What happens if none of the
iforelifconditions are true and there is noelse? - Can you have an
elifwithout anif? Why or why not? - Why does Python use indentation instead of curly braces like some other languages?
- If you write
if x > 5 and x < 10:, what range of numbers would make this condition true? - What is the difference between
andandor? Give a real-world example of each. - Why is it important to put the most specific
elifconditions first?
ifchecks a condition. If it isTrue, the indented block runs.elifchecks another condition if the previous ones wereFalse.elsecatches everything that did not match any condition above.- Comparison operators (
==,!=,<,>,<=,>=) returnTrueorFalse. - Logical operators (
and,or,not) let you combine conditions. - The colon
:and correct indentation are essential in Python. - Nested if statements allow decisions within decisions.
- Truth tables show all possible outcomes for logical operators.
Chapter Summary
In this chapter, you learned how to make your programs choose between different paths using selection. Here is a quick recap:
- An
ifstatement checks a condition and runs a block of code only if it isTrue. eliflets you check additional conditions. You can have as many as you need.elseis the safety net — it runs when nothing else matched. It must come last.- Comparison operators (
==,!=,<,>,<=,>=) compare values and return a boolean. - Logical operators (
and,or,not) combine or invert conditions. - Truth tables show all possible outcomes for
and,or, andnot. - Nested if statements handle situations where one decision depends on another.
- Indentation defines which lines belong to which block — it is not optional in Python.
Exam-Style Questions
These questions are similar to what you might see in your GCSE Computer Science exam. Try to answer on paper before revealing the answer.
Question 1 (2 marks)
Describe the purpose of an elif statement in Python.
Mark scheme:
- An
elifstatement allows the program to check an additional/alternative condition (1 mark) - ...if the previous
if(orelif) condition wasFalse/ not met. (1 mark)
Example answer: An elif (short for "else if") is used to check another condition when the preceding if or elif condition evaluated to False. This allows a program to choose between more than two possible outcomes.
Question 2 (2 marks)
Complete the truth table for the AND operator:
| A | B | A AND B |
|---|---|---|
True | True | ? |
True | False | ? |
False | True | ? |
False | False | ? |
Mark scheme: All four correct = 2 marks. Two or three correct = 1 mark.
| A | B | A AND B |
|---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Remember: with AND, the result is only True when both inputs are True.
Question 3 (3 marks)
A student writes a program to check if a number is between 1 and 100 (inclusive). They write:
number = 500
if number > 1 or number < 100:
print("The number is between 1 and 100")
else:
print("The number is NOT between 1 and 100")
Explain why this does not work correctly and write the corrected code.
Mark scheme:
- The student used
orinstead ofand. (1 mark) - With
or, the condition is true if either part is true. Since 500 is greater than 1, the first part isTrue, making the whole conditionTrueeven though 500 is not between 1 and 100. (1 mark) - Corrected code:
if number >= 1 and number <= 100:(1 mark)
Example answer: The student used or but should have used and. With or, the condition is True when at least one part is true. The number 500 is greater than 1, so the first part is True, and the whole condition becomes True. The corrected condition is: if number >= 1 and number <= 100:. This ensures both conditions must be true.
Extra Resources
Sharpen your selection skills with these resources:
- GCSE Topic 6: Control Flow — Selection and iteration with interactive Python code editors and challenges
- Program Builder — Drag-and-drop code construction challenges
- BBC Bitesize Edexcel Computer Science — Selection revision notes and exam practice
- W3Schools: Python If...Else — Interactive examples and exercises on conditional statements
- W3Schools: Python Operators — Full reference for comparison and logical operators
What is Next?
Now that your programs can make decisions, it is time to learn how to repeat actions. In Chapter 5: Loops, you will discover for loops and while loops — the tools that let your programs do things over and over without writing the same code hundreds of times.