The answersDownload the PDF
Worksheet

F2.4 Nested selection and match

Decisions and loops · GCSE · OCR J277 2.2.1, AQA 8525 3.2.2, Edexcel 1CP2 6.2.2 · about 15 min

BugBotLab
NameClassDate

What this lesson is about

Decisions inside decisions, and choosing by exact value with a case statement.

Questions 6 marks in all

  1. [1 mark]What does this program print?

    d = 60
    b = 10
    if d < 30:
        if b < 20:
            print("stuck and flat")
        else:
            print("stuck")
    else:
        if b < 20:
            print("free but flat")
        else:
            print("free")
  2. [1 mark]Which else does an else belong to in nested selection?

    1. AThe if it lines up with
    2. BAlways the first if in the program
    3. CAlways the nearest if above it, whatever the indentation
    4. DThe last if in the program
  3. [1 mark]What does this program print?

    command = "left"
    match command:
        case "forward":
            print("f")
        case "left" | "right":
            print("sideways")
        case _:
            print("unknown")
  4. [1 mark]What does case _: do in a match?

    1. AMatches any value not matched above, like else
    2. BMatches an empty string
    3. CEnds the match
    4. DCauses an error
  5. [1 mark]OCR's Exam Reference Language writes a case statement with which keyword? (one word)

  6. [1 mark]Which is the same as if a > 30: if b > 50: print("go") (with no else parts)?

    1. Aif a > 30 and b > 50: print("go")
    2. Bif a > 30 or b > 50: print("go")
    3. Cif not a > 30: print("go")
    4. Dif a > 30: print("go")

The task: command mode

The robot asks Which way? and then How far? . Use match (or elif) on the direction to drive that far: forward, back, left or right. For any other word, print unknown and do not move. The task answers right and 20; your program must work for any answers, so do not type them in.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

command = input("Which way? ")
far = float(input("How far? "))

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/f2-4-nested-selection-and-match/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Add a stop command that turns the LED red and does not move.
  2. Make the robot refuse to drive forward when there is less than 30 cm of room, using a nested if inside that case.
  3. Rewrite the command program with elif instead of match. Which is easier to read?