If…Elif…Else Conditions⌗

Objectives⌗

  1. Understand how if...elif...else statements work.
  2. Use multiple conditions to choose between different actions.
  3. Create interactive drawings using keyboard input.

Quick Recall⌗

If Statement⌗

An if statement runs code only when a condition is True.

if condition:
    # Runs when condition is True

If…Else Statement⌗

An if...else statement chooses between two actions.

if condition:
    # Runs when condition is True
else:
    # Runs when condition is False

Objective 1 - Understanding If…Elif…Else⌗

An if...elif...else statement allows us to check multiple conditions and choose between different actions.

  • if checks the first condition.
  • elif checks another condition if the previous condition was False.
  • else runs when all the conditions are False.

Syntax⌗

if condition1:
    # Runs when condition1 is True
elif condition2:
    # Runs when condition2 is True
else:
    # Runs when both conditions are False

Only one block of code runs. Python checks the conditions from top to bottom and executes the first matching block.

Example⌗

grade = 85

if grade >= 90:
    print("Excellent")
elif grade >= 70:
    print("Good")
else:
    print("Keep Practicing")

Since grade is 85, the output will be:

Good

Objective 2 - Using If…Elif…Else with Keyboard Input⌗

We can also use if...elif...else with keyboard input to make our drawings interactive.

For example:

if key == "R":
    color = "red"
elif key == "B":
    color = "blue"
else:
    color = "gray"
  • Pressing R makes the color red.
  • Pressing B makes the color blue.
  • Pressing any other key makes the color gray.

Starter Template⌗

Use this template for both activities.

from animation import run_sketch

def draw(p, key):

    # Draw the sketch here


run_sketch(draw, bgcolor="lightblue")

Guided Activity - Traffic Light⌗

Create an interactive traffic light using if...elif...else.

Traffic light

Instructions:

  • Press R to turn on the red light.
  • Press Y to turn on the yellow light.
  • Press G to turn on the green light.
  • Only one light should be on at a time.
  • Use if...elif...else to change the light colors.

Independent Activity - Battery Indicator⌗

Create an interactive battery indicator that displays different battery levels.

Battery indicator

Instructions:

  • Press L to show a low battery level (red).
  • Press M to show a medium battery level (yellow).
  • Press H to show a high battery level (green).
  • Use if...elif...else to set the battery level and color.

Submission⌗

Submit both Python files to Google Classroom:

  • Guided Activity - Traffic Light
  • Independent Activity - Battery Indicator

Make sure both programs run correctly before submitting.