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:

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

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.

Predict First! The code checks if 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?
You can drive!
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.
Python Code
age = 16

if age >= 16:
    print("You can drive!")

print("Thanks for checking.")
(click "Run Code" to see output)
Try this: Change 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.

Python Code
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.")
(click "Run Code" to see output)
Try this: Change 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.

Predict First! The score is 75. Python checks conditions from top to bottom. Is 75 >= 90? Is 75 >= 70? Is 75 >= 50? Which branch will run — and will Python keep checking after it finds a match?
Your score is 75
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.
Python Code
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)
(click "Run Code" to see output)
Try this: Try scores of 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.

Python Code
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.")
(click "Run Code" to see output)
Try this: Change 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.

Python Code
# 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.")
(click "Run Code" to see output)
Try this: Change 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.

Python Code
# 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.")
(click "Run Code" to see output)
Try this: Change 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.

Python Code
# You can see boolean values directly
print(10 > 5)     # True
print(3 == 7)     # False
print(4 != 4)     # False
print(6 <= 6)     # True
(click "Run Code" to see output)

Comparison Operators

These operators compare two values and return True or False. In your GCSE, these are also called relational operators:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 7True
>Greater than10 > 20False
<=Less than or equal to5 <= 5True
>=Greater than or equal to4 >= 9False

Logical Operators: Combining Conditions

Sometimes one condition is not enough. You can combine conditions using and, or, and not:

Python Code
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
(click "Run Code" to see output)

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:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

OR Truth Table

With or, the result is True when at least one input is True:

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

NOT Truth Table

With not, the result is simply the opposite of the input:

Anot A
TrueFalse
FalseTrue
Python Code
# 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
(click "Run Code" to see output)

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.

Key Concept: The colon and indentation are essential Every 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.
Python Code
# 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)
(click "Run Code" to see output)

Common Misconception: = vs ==

Watch out! A very common mistake is confusing = 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.

Python Code
# 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.")
(click "Run Code" to see output)
Did You Know? — elif is not universal Python's 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!
Did You Know? — Chained comparisons In Python, you can chain comparisons like maths. Instead of writing 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!
Did You Know? — George Boole and Boolean logic The 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:

Key Vocabulary

Make sure you understand these key terms — they will appear in your GCSE exam:

TermDefinition
SelectionA programming construct where the program chooses which path to follow based on a condition.
ConditionAn expression that evaluates to True or False. For example, age >= 18.
BooleanA data type with only two possible values: True or False. Named after George Boole.
Comparison OperatorAn operator that compares two values and returns a boolean. Also called a relational operator. Examples: ==, !=, <, >.
Relational OperatorAnother name for a comparison operator. Used in the OCR and Edexcel specifications.
Logical OperatorAn operator that combines or modifies boolean values: and, or, not.
ifA keyword that starts a conditional block. The code inside runs only if the condition is True.
elifShort for "else if". Checks an additional condition when the previous one was False.
elseA catch-all block that runs when none of the preceding conditions were True. Must come last.
IndentationThe spaces at the start of a line that tell Python which block a line belongs to. Typically four spaces.
Nested SelectionAn if statement placed inside another if statement. Used when a second decision depends on the first.
Truth TableA 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:

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.

Python Code
# 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.")
(click "Run Code" to see output)
Try this: Test with scores of 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

The Top 5 If Statement Mistakes
  1. Using = instead of == in conditions. Remember: = assigns, == compares. Writing if score = 90: causes a SyntaxError.
  2. Forgetting the colon : after if/elif/else. Every condition line must end with a colon. Missing it causes a SyntaxError.
  3. 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.
  4. The order of elif matters. Python runs the first true condition. If you put score >= 50 before score >= 90, a score of 95 would match the wrong branch. Always put the most specific conditions first.
  5. Using elif after else. The else block must always be the last branch. You cannot write elif after else — Python will give you a SyntaxError.

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?

Guided

Write a program that checks whether a number is positive, negative, or zero, and prints an appropriate message for each case.

Pseudocode

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"

Python Code
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))
(click "Run Code" to see output)
Hint

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 Guided

A 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.

Pseudocode

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

Python Code
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")
(click "Run Code" to see output)
Hint

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-Ended

Create 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.

Pseudocode

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"

Python Code
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.")
(click "Run Code" to see output)
Hint

This exercise is open-ended — be creative! Ideas to extend it:

  • Add a second decision after the first one.
  • Use or to accept different capitalizations (e.g., if choice == "red" or choice == "Red":).
  • Add a scoring system with a points variable.

Exercise 4: Login System

Partially Guided

Write 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."
Pseudocode

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."

Python Code
# 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(...)
(click "Run Code" to see output)
Hint

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-Ended

Create 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.

Pseudocode

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..."

Python Code
# 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!
(click "Run Code" to see output)
Hint

Ideas to extend the adventure:

  • Add a third room with a new decision (fight a dragon or sneak past?).
  • Add a health variable and check if health <= 0: for game over.
  • Use and to 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.

  1. What is the difference between = and == in Python?
  2. What happens if none of the if or elif conditions are true and there is no else?
  3. Can you have an elif without an if? Why or why not?
  4. Why does Python use indentation instead of curly braces like some other languages?
  5. If you write if x > 5 and x < 10:, what range of numbers would make this condition true?
  6. What is the difference between and and or? Give a real-world example of each.
  7. Why is it important to put the most specific elif conditions first?
Key Takeaways
  • if checks a condition. If it is True, the indented block runs.
  • elif checks another condition if the previous ones were False.
  • else catches everything that did not match any condition above.
  • Comparison operators (==, !=, <, >, <=, >=) return True or False.
  • 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:

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.

Reveal Answer

Mark scheme:

  • An elif statement allows the program to check an additional/alternative condition (1 mark)
  • ...if the previous if (or elif) condition was False / 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:

ABA AND B
TrueTrue?
TrueFalse?
FalseTrue?
FalseFalse?
Reveal Answer

Mark scheme: All four correct = 2 marks. Two or three correct = 1 mark.

ABA AND B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

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:

Python Code
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")
(click "Run Code" to see output)

Explain why this does not work correctly and write the corrected code.

Reveal Answer

Mark scheme:

  • The student used or instead of and. (1 mark)
  • With or, the condition is true if either part is true. Since 500 is greater than 1, the first part is True, making the whole condition True even 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:

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.