Skip to the content

EXECUTED, WITH ASSERTIONS

This program was run during verification and its results asserted.

The code

Straight from labs/course-3-python/02c_loop_control.py, unchanged.

"""Experiment 2(c): Illustrate the loop control statements break, continue
and pass.

  break    -- leave the loop immediately
  continue -- skip the rest of this iteration, go to the next
  pass     -- do nothing; a syntactic placeholder where a statement is required

Syllabus: Course 3, Unit 2 -- loop control statements.
"""

# Step 1: break
print("break -- stop as soon as we reach 5")
for i in range(1, 11):
    if i == 5:
        break
    print(f"  {i}", end="")
print("\n")

# Step 2: continue
print("continue -- skip the even numbers")
for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(f"  {i}", end="")
print("\n")

# Step 3: pass
print("pass -- placeholder, the loop body does nothing for multiples of 3")
for i in range(1, 11):
    if i % 3 == 0:
        pass          # a branch we have not written yet; keeps the code valid
    else:
        print(f"  {i}", end="")
print("\n")

# Step 4: else on a loop
print("else with a loop -- runs only when the loop was NOT broken out of")
for i in range(1, 4):
    print(f"  iteration {i}")
else:
    print("  loop finished without a break")

Where this sits

One experiment from the Python Programming and Data Structures lab. The rest of them, and the theory behind this one, are on the lab page.