Understanding Control Structures: While & If-Else

Concept: The Apple Factory

Imagine you are managing a quality control conveyor belt. Your logic is cleanly divided into two specific responsibilities:

1

The Loop (Duration)

"How long should I keep working?" You continue inspecting as long as the conveyor belt is not empty. When it's empty, you stop. We use a while loop because we don't know the exact count in advance.

2

The Condition (Selection)

"What do I do with this item?" For each apple, check its color. If it is Red, pack it in a box. Otherwise (Green), send it to the juicer.

Algorithm Execution
belt = ['R', 'G', 'R']
while len(belt) > 0:
apple = belt.pop(0)
if apple == 'R':
packed += 1
else:
juiced += 1

Memory State (記憶體狀態)

🍎🍏🍎
-
0
0

Trace Table (追蹤表)

Action belt apple packed juiced

Think & Link

What would happen if we swapped the while condition and the if condition? For example, if we wrote `while apple == 'R'`? Draft your logic below.

Knowledge Check

In a `while` loop processing an array, if an item triggers the else branch, what happens immediately after the `else` block finishes executing?