Control Flow: Decisions and Loops

EE1021 Programming for Engineers · Lecture 2 · 2026–2027

Basri Erdogan

Lecture Goals

  1. Build decisions with if / elif / else and correct indentation
  2. Trace and write while loops that make progress toward a stopping condition
  3. Iterate over range() and strings with for loops
  4. Choose a for or while loop, and use break to stop reading input when the user enters a special stop value (such as -1)
  5. Apply three reusable patterns: accumulate, count, and build

Retrieval Warm-Up

Predict the output before running the code.

x = 4
y = 7

print(x < y)
print((x + y) % 2)
print("sensor"[1:4])

Check: True, 1, and "ens".
Bridge to today: a Boolean result such as x < y can decide which block runs.

Part 1: Decisions

Conditions Produce Boolean Values

temperature = 82

too_hot = temperature > 75
safe = temperature <= 75
  • Comparisons produce True or False.
  • Logical operators combine conditions.
has_power = True
is_connected = False

ready = has_power and is_connected
needs_help = not ready

ready is False; needs_help is True.

Branching Patterns

One-way decision

if condition:
    statements

Run the block only when the condition is True.

Two-way decision

if condition:
    statements
else:
    other_statements

Exactly one branch runs.

Multiple alternatives

if condition_1:
    statements
elif condition_2:
    other_statements
else:
    fallback_statements

Python selects the first true branch.

Engineering Decision: Battery Level

Rule: 50% or more → OK. 20% to 49% → Low. Below 20% → Charge now.

battery = 35   # charge in percent (0 to 100)

if battery < 0 or battery > 100:
    print("Invalid reading")
elif battery >= 50:
    print("OK")
elif battery >= 20:
    print("Low")
else:
    print("Charge now")

Python tests branches from top to bottom and stops after the first true condition. Here battery >= 50 is false, battery >= 20 is true, so the program prints Low.

Predict: what does the program print if battery = 10?

Check: Charge now. No condition above else is true.

Indentation Defines the Block

Python uses indentation as part of its syntax. Use four spaces for each level.

temperature = int(input("Temperature: "))

if temperature < -50:
    print("Invalid reading")
elif temperature > 75:
    print("High temperature")
else:
    print("Temperature is in range")

print("Check finished")

Only the indented statement under the selected branch runs. The final print() is aligned with if, so it runs after whichever branch is selected.

Engineering Checkpoint: Test the Boundaries

Use the battery program to predict one output for each test case.

battery Why test it?
-1 just below the valid range
101 just above the valid range
50 exact OK limit
49 just below the OK limit
20 exact Low limit
19 just below the Low limit

Verify: trace the branches from top to bottom before running the program.

Check: Invalid reading, Invalid reading, OK, Low, Low, Charge now.

Part 2: Repetition

while: Repeat While a Condition Is True

initialize state
while condition:
    statements
    update state

A reliable while loop has three parts:

  1. A state variable initialized before the loop
  2. A condition checked before each iteration
  3. An update that moves the state toward termination

Trace a while Loop

n = 0

while n < 8:
    print(n)
    n += 2
Before test n < 8 Printed Updated n
0 True 0 2
2 True 2 4
4 True 4 6
6 True 6 8
8 False — —

The loop stops when the condition becomes False.

Prevent Infinite Loops

Problem: no progress

n = 0
while n < 3:
    print(n)

n never changes, so n < 3 remains True.

Fix: update the state

n = 0
while n < 3:
    print(n)
    n += 1

Before running a while loop, identify what will make its condition false.

for: Iterate Over a Sequence

Values generated by range()

for sample_number in range(4):
    print("Sample", sample_number)

The loop variable receives 0, 1, 2, and 3.

Characters in a string

for char in "EE1021":
    print(char)

A for loop is not limited to numeric counters.

range(start, stop, step)

The stop value is excluded.

Expression Generated values
range(5) 0, 1, 2, 3, 4
range(2, 6) 2, 3, 4, 5
range(2, 11, 2) 2, 4, 6, 8, 10
range(5, 0, -1) 5, 4, 3, 2, 1

Defaults: start = 0, step = 1.

Range and Off-by-One Checkpoint

total = 0
for value in range(4, 21, 4):
    total += value
print(total)

Predict:

  1. Which values are generated?
  2. Why is 20 included?
  3. What is printed?

Check: 4, 8, 12, 16, 20; the next value would exceed the stop value 21; the total is 60.

break: Stop on a Sentinel

Use a sentinel value to signal that input is finished.

total = 0.0

while True:
    reading = float(input("Reading (-999 to stop): "))
    if reading == -999:
        break
    total += reading

print("Total:", total)

break exits the innermost loop immediately. Statements after the loop still run.

Choosing for or while

Prefer for when:

  • Iterating over a known sequence
  • Repeating a known number of times
  • Traversing characters in a string
  • Using values generated by range()

Prefer while when:

  • Repeating until a condition changes
  • The number of iterations is unknown
  • Reading until a sentinel value
  • Validating input until it is acceptable

Loop Checkpoint

total = 0

for value in range(1, 6):
    if value % 2 == 0:
        total += value

print(total)

Trace: list the generated values, identify which ones pass the if, and predict the output.

Check: range(1, 6) generates 1, 2, 3, 4, 5; only 2 and 4 are added; the output is 6.

Part 3: Reusable Problem Patterns

Pattern 1: Accumulate a Total

Initialize the accumulator before the loop and update it inside the loop.

total = 0

for value in range(1, 6):
    total += value

print("Total:", total)

Trace the accumulator: 0 → 1 → 3 → 6 → 10 → 15.

Pattern 2: Count Matches

text = "Programming for Engineers"
vowel_count = 0

for char in text:
    if char in "aeiouAEIOU":
        vowel_count += 1

print("Vowels:", vowel_count)

The counter changes only when the current character satisfies the condition.

Pattern 3: Build a New String

word = "Hello"
modified = ""

for char in word:
    if char in "aeiouAEIOU":
        modified += "*"
    else:
        modified += char

print(modified)

The result is H*ll*. Each iteration contributes one character to the new string.

Engineering Example: Temperature Monitor

Read an unknown number of measurements and report how many exceed the limit.

limit = 75.0
high_count = 0

while True:
    temperature = float(input("Temperature (-999 to stop): "))
    if temperature == -999:
        break
    if temperature > limit:
        high_count += 1

print("High readings:", high_count)

This combines a sentinel-controlled while loop, branching, and a counter.

Convert a for Loop to while

for value in range(2, 7, 2):
    print(value)
value = 2
while value < 7:
    print(value)
    value += 2

The while version makes initialization, condition, and update explicit.

Five-Minute Exit Ticket

Answer without running Python first.

  1. Which branch runs when x = 12 in if x < 0 ... elif x < 10 ... else ...?
  2. What values does range(3, 11, 3) generate?
  3. What single missing line causes this loop to terminate?
n = 0
while n < 3:
    print(n)
    # missing line

Check: the else branch; 3, 6, 9; n += 1.

Summary

  • Conditions evaluate to True or False and select branches.
  • Python uses indentation to define blocks.
  • A reliable while loop has initialization, a condition, and an update.
  • A for loop iterates over a sequence such as range() or a string.
  • range() excludes its stop value.
  • break exits the innermost loop immediately.
  • Accumulating, counting, and building a result are reusable loop patterns.