Control Flow and Functions

Control flow is the path taken through a program. Without control flow, a program can only run statements from top to bottom once. With selection and iteration, a program can make decisions and repeat work.

Caption: Sequence follows one path, selection chooses a branch, and iteration returns to a condition until the stopping path is taken.

Algorithmic Representations

Before coding, an algorithm may be represented using pseudocode or a flowchart. Pseudocode describes logic using structured English and programming constructs; it is not Python and should not depend on Python punctuation.

INPUT mark
IF mark >= 50 THEN
    OUTPUT "Pass"
ELSE
    OUTPUT "Fail"
ENDIF

A flowchart uses standard symbols: terminators for start/end, parallelograms for input/output, rectangles for processing, diamonds for decisions, and arrows for control flow.

Sequence

Sequence means statements run in order.

width = 8
height = 5
area = width * height
print(area)

The order matters. area cannot be calculated before width and height have values.

Selection

Selection chooses between paths using a condition.

if mark >= 50:
    result = "Pass"
else:
    result = "Fail"

A condition should evaluate to True or False.

Common comparison operators:

OperatorMeaning
==equal to
!=not equal to
<less than
<=less than or equal to
>greater than
>=greater than or equal to

Combine conditions with and, or, and not:

if mark >= 0 and mark <= 100:
    print("valid mark")

Designing Conditions

A good condition says exactly what must be true for a branch to run.

Weak condition:

if age:
    print("age entered")

This relies on Python truthiness and may be unclear for beginners. A clearer condition is:

if age != "":
    print("age entered")

For syllabus and exam work, prefer explicit logic unless the question is specifically about Python truth values.

Iteration

Iteration repeats a block of statements.

Use a for loop when iterating over a known sequence:

scores = [72, 85, 68]
total = 0
 
for score in scores:
    total = total + score

Use a while loop when repetition depends on a condition:

number = 1
 
while number < 100:
    number = number * 2

For while loops, always check:

  • what makes the condition true initially;
  • what changes inside the loop;
  • why the loop eventually stops.

Loop Invariants

A loop invariant is an idea that remains true each time the loop repeats. It helps explain why the loop works.

scores = [72, 85, 68]
total = 0
 
for score in scores:
    total = total + score

After each iteration, total is the sum of the scores processed so far. That invariant explains the purpose of the loop.

Range and Off-by-One Errors

range(5) produces 0, 1, 2, 3, 4.

for i in range(5):
    print(i)

If you need 1, 2, 3, 4, 5, write:

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

Off-by-one errors happen when a loop starts or stops one step too early or too late.

Repeat-Until and While Logic

In pseudocode, a WHILE loop tests before the body and may execute zero times. A REPEAT ... UNTIL loop tests after the body, so it executes at least once.

REPEAT
    INPUT choice
UNTIL choice = "Y" OR choice = "N"

Python has no direct repeat-until statement, but the same logic can be written using while True and break when appropriate.

Break, Continue, and Pass

break exits a loop early.

for value in values:
    if value < 0:
        break

continue skips the rest of the current iteration.

for value in values:
    if value < 0:
        continue
    print(value)

pass does nothing. It can be used as a temporary placeholder while designing code.

Decision Tables

A decision table is useful when several Boolean conditions combine to determine actions. Each column represents one rule, showing one combination of conditions and the resulting action.

For two conditions there are up to combinations; for three conditions there are up to . After listing all combinations, redundant rules may be merged using a dash to mean “condition does not matter”.

Decision tables are best used during analysis. They help ensure that no combination is overlooked before the logic is translated into selection statements.

Functions and Procedures

A function packages a task under a name.

Caption: A function call passes argument values into parameters and may send a return value back to the caller.

def calculate_average(scores):
    total = 0
    for score in scores:
        total = total + score
    return total / len(scores)

The parameter scores receives the input list. The return statement sends the result back to the caller.

A procedure is a subprogram used mainly for its action rather than for returning a value. In Python, procedures are still written with def, but they may not return a meaningful value. If execution reaches the end without a return value, Python returns None.

def print_result(name, mark):
    print(name, "scored", mark)

Parameters, Arguments, and Scope

A parameter is the name written in a function definition. An argument is the actual value supplied in a call.

def rectangle_area(width, height):  # parameters
    return width * height
 
area = rectangle_area(8, 5)         # arguments

Variables created inside a function are normally local to that call. Keeping state local reduces accidental interference between different parts of a program.

Decomposition

Decomposition means breaking a problem into smaller tasks.

Instead of one long block:

name = input("Name: ")
mark = int(input("Mark: "))
if mark >= 50:
    print(name, "Pass")
else:
    print(name, "Fail")

Use named functions:

def is_pass(mark):
    return mark >= 50
 
 
def result_label(mark):
    if is_pass(mark):
        return "Pass"
    return "Fail"

This makes the logic easier to test.

Tracing Example

Trace:

Caption: A loop trace records the condition and the variable updates after each repetition.

count = 0
number = 4
 
while number < 20:
    number = number * 2
    count = count + 1
Stepnumbercountnumber < 20
start40True
after 1st iteration81True
after 2nd iteration162True
after 3rd iteration323False

The loop stops when number becomes 32.

For a beginner, the safest loop-tracing method is:

  1. Write the initial values before the loop starts.
  2. Test the condition before entering the loop.
  3. Run the whole loop body once.
  4. Record every variable that changed.
  5. Test the condition again before deciding whether to repeat.

Common Bugs

  • Using = instead of == in a condition.
  • Forgetting to update the condition variable in a while loop.
  • Using range(n) when the intended last value is n.
  • Returning too early from inside a loop.
  • Making a function do too many unrelated jobs.
  • Using a variable before it has been assigned.

Check Your Understanding

Try these before looking back at the explanations:

  1. What is the difference between selection and iteration?
  2. Why must a while loop usually change at least one variable used in its condition?
  3. In def result_label(mark):, what is mark called?
  4. Why is return different from print()?

Answers:

  1. Selection chooses between paths once; iteration repeats a path.
  2. Without a relevant change, the condition may stay true forever.
  3. A parameter.
  4. return sends a value back to the caller; print() displays text but does not pass a value back for later calculation.