Area 2.6

Actions (Control Structures)

Master the three fundamental control structures: sequence, selection, and iteration. Learn how to control program flow and make decisions in your code.

3
Control Types
8
Variations
~2hrs
Study Time

Learning Objectives

  • Understand the three fundamental control structures in programming
  • Apply sequence for step-by-step execution of instructions
  • Use selection (if-else, match-case) for decision making in programs
  • Implement iteration (for and while loops) for repetitive tasks
  • Evaluate the benefits and drawbacks of each control structure
  • Choose appropriate control structures for different programming scenarios

Fundamental Control Structures

Sequence

Instructions executed one after another in a specific order

Benefits:

  • Easy to read and debug
  • Predictable execution order
  • Clear program flow
  • No complex logic required

Drawbacks:

  • Cannot make decisions
  • No flexibility in execution
  • Cannot handle varying conditions
  • Limited problem-solving capability

When to Use:

Simple calculations, data input/output, basic program setup, linear processes

Python Examples:

# Sequence - steps executed in order
print("Welcome to the calculator")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print(f"The sum is: {result}")
print("Thank you for using the calculator")

# Each line executes after the previous one completes

Selection (if-else)

Choose different paths based on conditions and decision points

Benefits:

  • Enables decision making
  • Handles different scenarios
  • Flexible program behavior
  • Responds to user input

Drawbacks:

  • Can become complex with many conditions
  • May lead to deeply nested code
  • Harder to test all paths
  • Potential for logic errors

When to Use:

User input validation, different outcomes based on conditions, menu systems, error handling

Python Examples:

# Selection - if/elif/else statements
age = int(input("Enter your age: "))

if age < 13:
    category = "child"
    price = 5.00
elif age < 65:
    category = "adult"
    price = 10.00
else:
    category = "senior"
    price = 7.50

print(f"Category: {category}, Price: £{price}")

# Match-case (Python 3.10+)
match category:
    case "child":
        print("Special kids menu available!")
    case "adult":
        print("Full menu access")
    case "senior":
        print("Senior discount applied")

Iteration (Loops)

Repeat instructions while conditions are true or for specific counts

Benefits:

  • Eliminates code duplication
  • Handles unknown quantities
  • Processes collections efficiently
  • Reduces programming effort

Drawbacks:

  • Risk of infinite loops
  • Can be complex to debug
  • Performance concerns with large iterations
  • Logic errors affect multiple iterations

When to Use:

Processing lists, repetitive calculations, user input validation, counting operations

Python Examples:

# For loop - known number of iterations
print("Countdown:")
for i in range(5, 0, -1):
    print(i)
print("Launch!")

# For loop with collections
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"I like {fruit}")

# While loop - condition-based
password = ""
attempts = 0
max_attempts = 3

while password != "secret123" and attempts < max_attempts:
    password = input("Enter password: ")
    attempts += 1

if password == "secret123":
    print("Access granted!")
else:
    print("Too many failed attempts")

Selection Statement Types

Simple if

if condition:
if age >= 18:
    print("Can vote")

Single condition check

if-else

if condition: # code else: # code
if score >= 60:
    print("Pass")
else:
    print("Fail")

Two alternative outcomes

if-elif-else

if condition1: elif condition2: else:
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

Multiple conditions

match-case

match variable: case value1: case value2:
match day:
    case "Monday":
        print("Start of week")
    case "Friday":
        print("TGIF!")

Multiple exact value matches

Iteration (Loop) Types

for loop (range)

Known number of iterations

Syntax:

for i in range(start, stop, step):

Example:

for i in range(1, 11):
    print(i)

Termination:

Automatically after specified count

for loop (collection)

Processing each item in a list

Syntax:

for item in collection:

Example:

for name in names:
    print(f"Hello {name}")

Termination:

After processing all items

while loop

Condition-based repetition

Syntax:

while condition:

Example:

while user_input != "quit":
    user_input = input("Command: ")

Termination:

When condition becomes False

do-while (simulation)

Execute at least once

Syntax:

while True: # code if not condition: break

Example:

while True:
    choice = input("Continue? (y/n): ")
    if choice == "n":
        break

Termination:

Break statement when condition met

Learning Activities

Control Flow Design Challenge

Design
45 minutes

Design programs using different combinations of sequence, selection, and iteration

Loop Optimization Workshop

Optimization
40 minutes

Compare for loops vs while loops for different scenarios and optimize performance

Nested Structure Practice

Practice
50 minutes

Create programs with nested loops and conditional statements