12  Python Conditional Statements

TipLearning Objectives
  • Learn about conditional statements
  • Learn how to use them and their syntax

12.1 Conditionals

Conditional statements are important because they let a program make decisions. The program can evaluate conditions and use them to choose what action to take. Conditions can be based on user input or data values, for example. This makes programs flexible and able to respond to different situations instead of doing the same thing every time.

Conditionals in Python allow you to execute different blocks of code based on conditions with boolean outputs. By boolean outputs, we mean that the condition must evaluate to True or False.

This is mainly done using if, elif, and else statements. These are read from top to bottom. You do not always need to have elif and else statements, but they are good to have and can be used to catch unexpected values.

if Statement:

The if statement evaluates a condition which returns a boolean (True or False). If the condition is True, the block of code inside the if statement is executed.

elif Statement:

The elif (short for “else if”) statement allows you to check multiple conditions. It follows an if statement and is executed if the previous conditions were False and its own condition is True.

else Statement:

The else statement is used to execute a block of code if none of the preceding if or elif conditions were True.

Syntax

if condition:
    print(x) # Code to execute if condition is True
elif another_condition:
    print(y) # Code to execute if first condition is False and another_condition is True
else:
    print(z) # Code to execute if all conditions are False

Note the colon and indentation used in the above example.

  • Indentation is also used to nest conditionals and loops in Python, and incorrect indentation is a common cause of errors.

Here are two examples of using conditionals:

Example 1: Temperature check

temperature = 25

if temperature > 30:
    print("It's a hot day.")
    # Checks if temperature is greater than 30. If True, prints "It's a hot day."
elif temperature < 10:
    print("It's a cold day.")
    # If the first condition is False, checks if temperature is less than 10.
else:
    print("It's a pleasant day.")
    # If both conditions are False, the else block executes.
It's a pleasant day.

Example 2: Traffic light system

light_colour = "yellow"

if light_colour == "red":
    print("Stop!")
elif light_colour == "yellow":
    print("Prepare to stop or proceed with caution.")
elif light_colour == "green":
    print("Go!")
else:
    print("Signal error: unknown colour.")
Prepare to stop or proceed with caution.

With very simple conditions, Python has a shorthand that is useful. You can write code like:

temperature = 25
print("It's a hot day") if temperature > 30 else (print("It's a cold day") if temperature < 10 else print("It's a pleasant day"))
# These are known as ternary operators – there is no elif
It's a pleasant day

Ternary expressions are best kept simple. Nesting them can reduce readability, so regular if/elif/else statements are often clearer.

Operators

Operators are a key tool when using conditional statements in Python. Remind yourself about them and their order of precedence.

ExerciseExercise 1 - Discussion: Operators with conditionals

Level:

Which types of operators are most useful when using conditional statements in Python?

The most useful operators with conditional statements are:

  1. Comparison Operators: Used to compare two values.
    • == (Equal to)
    • != (Not equal to)
    • < (Less than)
    • > (Greater than)
    • <= (Less than or equal to)
    • >= (Greater than or equal to)
  2. Logical Operators: Used to combine multiple conditions.
    • and (Returns True if both statements are true)
    • or (Returns True if at least one statement is true)
    • not (Reverses the result, returning False if the result is true)
  3. Membership Operators: Useful for checking if a value exists in a sequence (list, tuple, set, string).
    • in
    • not in
ExerciseExercise 2 - Mini conditionals check

Look at the following code:

x = 7

if x > 10:
    print("A")
elif x > 5:
    print("B")
elif x > 3:
    print("C")
else:
    print("D")

What would the output be?

Rewrite the statement to check the conditions independently.

The output would be B. - x > 10 (7 > 10) evaluates to False. - x > 5 (7 > 5) evaluates to True, so "B" is printed and the remaining elif and else blocks are skipped entirely.

Independent checks: To check conditions independently, replace elif with separate if statements:

x = 7

if x > 10:
    print("A")
if x > 5:
    print("B")
if x > 3:
    print("C")
B
C

Note: With independent if statements, both "B" and "C" will be printed because both 7 > 5 and 7 > 3 evaluate to True.

ExerciseExercise 3 - Examining conditional statements

Level:

  • What do the following if statements do?
  • How can you write complex conditions and make your code legible?

Some actual examples from code:

  1. Checking set membership and numerical properties:
if (len(x[0]) == 2) and not any(val % 10 in {0, 9} for val in x[0]):
    print("Valid pair selected.")
  1. Checking chosen coordinates for a grid selection:
selected_mode = coord_choice[0]

if (
    (selected_mode == (1, 1) and (0, 0) in grid_points and (1, 1) in grid_points) or
    (selected_mode == (1, 1) and (1, 0) in grid_points and (0, 1) in grid_points) or
    (selected_mode == (1, 0) and (1, 0) in grid_points and (0, 0) in grid_points) or
    (selected_mode == (1, 0) and (1, 1) in grid_points and (0, 1) in grid_points)
):
    print("Valid grid configuration!")

How might the second example be made clearer if you were rewriting it?

  1. Example 1: Checks if the first element of x contains exactly 2 items, AND ensures that no item in x[0] leaves a remainder of 0 or 9 when divided by 10 (i.e. no numbers ending in 0 or 9).
  2. Example 2: Checks whether a selected coordinate mode combined with specific pairs of coordinates present in grid_points forms a valid configuration.

How to make Example 2 clearer: The second example repeats tests for selected_mode == (1, 1) and selected_mode == (1, 0). We can make it cleaner and more readable by: - Grouping logic by selected_mode using an if/elif structure. - Using set comparisons or helper boolean variables.

Refactored example:

selected_mode = coord_choice[0]

# Extract presence checks into clearer variables or helper structures
if selected_mode == (1, 1):
    valid_pair_1 = (0, 0) in grid_points and (1, 1) in grid_points
    valid_pair_2 = (1, 0) in grid_points and (0, 1) in grid_points
    is_valid = valid_pair_1 or valid_pair_2
elif selected_mode == (1, 0):
    valid_pair_1 = (1, 0) in grid_points and (0, 0) in grid_points
    valid_pair_2 = (1, 1) in grid_points and (0, 1) in grid_points
    is_valid = valid_pair_1 or valid_pair_2
else:
    is_valid = False

if is_valid:
    print("Valid grid configuration!")
ExerciseExercise 4 - Cinema ticket pricing

Write a Python script that calculates ticket prices for a cinema based on a customer’s age: - Children (under 12 years old): £5 - Adults (ages 12 to 64 inclusive): £10 - Seniors (aged 65 and above): £7

Define an age variable and write an if/elif/else structure to print the appropriate price message.

age = 15  # Example test age

if age < 12:
    price = 5
elif age <= 64:
    price = 10
else:
    price = 7

print(f"Ticket price: £{price}")
Ticket price: £10
ExerciseExercise 5 - Smart heating controller

Write a Python script to control an automated heating system based on the current room temperature: - If the temperature is below 18°C, print "Heating ON". - If the temperature is between 18°C and 22°C (inclusive), print "Temperature optimal. Heating STANDBY". - If the temperature is above 22°C, print "Heating OFF".

Test your code using different temperature values.

temperature = 19.5  # Example test temperature

if temperature < 18:
    print("Heating ON")
elif temperature <= 22:
    print("Temperature optimal. Heating STANDBY")
else:
    print("Heating OFF")
Temperature optimal. Heating STANDBY
ExerciseExercise 6 - Online store delivery charges and discounts

Level:

Scenario: You are writing the checkout calculation logic for an online UK retailer.

Without using a provided starter template, create a script that calculates delivery charges and discounts according to these business rules:

  1. First, check if the total amount of the order is less than or equal to £0. If so, display an error message stating that the order total is invalid.
  2. For valid orders:
    • If the customer is a VIP member, delivery is always free (£0.00). In addition, if their order total is greater than £30.00, they receive a 10% discount on their order total.
    • If the customer is not a VIP member:
      • Orders of £50.00 or more qualify for free delivery (£0.00).
      • Orders under £50.00 incur a £4.99 delivery fee.
  3. Calculate and print a breakdown showing:
    • The original order total
    • The applied discount amount (if any)
    • The delivery fee
    • The final total amount to be paid
# Test variables
amount = 45.00
is_vip_customer = True

if amount <= 0:
    print("Error: Invalid order total. Amount must be greater than £0.")
else:
    discount = 0.0
    delivery_fee = 0.0

    if is_vip_customer:
        delivery_fee = 0.00
        if amount > 30.00:
            discount = amount * 0.10
    else:
        if amount >= 50.00:
            delivery_fee = 0.00
        else:
            delivery_fee = 4.99

    final_total = amount - discount + delivery_fee

    print("--- Order Summary ---")
    print(f"Original total: £{amount:.2f}")
    print(f"Discount:       £{discount:.2f}")
    print(f"Delivery fee:   £{delivery_fee:.2f}")
    print(f"Final total:    £{final_total:.2f}")
--- Order Summary ---
Original total: £45.00
Discount:       £4.50
Delivery fee:   £0.00
Final total:    £40.50
ExerciseExercise 7 - Exercise 6: Modifying the if else statement within the logic.py script of the expense calculator

Functions in Python can have conditional statements within them, to configure output behaviour depending on the input values.

The logic.py script contains the core logic for the expense calculator.

  1. What does the script do?
  2. Modify the function to also print a warning if the value remaining is lower than 10. Do this in a jupyter notebook and test your function

What does the script do?

The check_threshold function manages budget monitoring for spending categories 1. It looks up the spending threshold for a given category from the thresholds dictionary (defaulting to 0 if the category is not found). 2. If current_total exceeds limit, it alerts the user that they have gone over budget for that category. 3. If current_total is within limit, it calculates remaining = limit - current_total and prints a confirmation showing the category name, total spent, and remaining budget available.

Modified function and test code

def check_threshold(category, current_total, thresholds):
    """Handles the conditional logic for budget warnings."""
    limit = thresholds.get(category, 0)
    if current_total > limit:
        print(f"Warning: You have exceeded the {category} threshold!")
        print(f"Total spent in {category}: {current_total}")
    else:
        remaining = limit - current_total
        print(f"Added to {category}.")
        print(f"Total spent in {category}: {current_total}")
        print(f"Amount left for {category}: {remaining}")

        # Check if the remaining amount is less than 10
        if remaining < 10:
            print(
                f"Warning: Low budget! You have less than £10 remaining for {category}."
            )
        print()


# --- Testing the function ---
sample_thresholds = {"Groceries": 100, "Entertainment": 50}

# Sufficient budget remaining (remaining >= 10)
print("First test")
check_threshold("Groceries", 50, sample_thresholds)

# Low budget remaining (remaining < 10)
print("Second test")
check_threshold("Groceries", 95, sample_thresholds)

# Exceeded budget
print("Third test")
check_threshold("Groceries", 110, sample_thresholds)
First test
Added to Groceries.
Total spent in Groceries: 50
Amount left for Groceries: 50

Second test
Added to Groceries.
Total spent in Groceries: 95
Amount left for Groceries: 5
Warning: Low budget! You have less than £10 remaining for Groceries.

Third test
Warning: You have exceeded the Groceries threshold!
Total spent in Groceries: 110

The function would be further improved with better docstring comments

12.2 Summary

TipKey Points
  • Conditional statements allow complex decision making.
  • Conditions use if, elif, and else statements.
  • Unlike other languages, Python uses indentation (not curly brackets) to group statements into blocks.
  • Conditionals are evaluated linearly starting with if, followed by any elif statements, and finally else. Once a condition is met, subsequent conditions are skipped.