Day 4 – Loops & Flow Control (for, while, break, continue)

 

🔁 Day 4 – Loops & Flow Control (for, while, break, continue)

1. Learning Objectives

By the end of Day 4, you will be able to:

  • Use for loops to iterate over a sequence (list, range, string).
  • Use while loops to repeat until a condition changes.
  • Control loop execution with break (exit early) and continue (skip to next iteration).
  • Apply loops to real AEC tasks: summing loads, generating floor levels, automating repeated checks.

2. Concept Explanation

2.1 The for Loop

The for loop iterates over each item in a sequence (list, tuple, string, or range).

for variable in sequence:
    # code to run for each item

AEC examples of sequences you’ll loop over:

  • A list of storey heights
  • A range of floor numbers
  • A list of beam spans
  • A string of a project code

range() function

range(start, stop, step) generates a sequence of integers.

CallProduces
range(5)0, 1, 2, 3, 4
range(1, 5)1, 2, 3, 4
range(1, 10, 2)1, 3, 5, 7, 9

Used often to loop a fixed number of times:

for floor in range(1, 11):   # floors 1 to 10
    print(f"Processing floor {floor}")

2.2 The while Loop

Repeats a block while a condition is True.
Warning: ensure the condition eventually becomes False to avoid infinite loops.

while condition:
    # code to repeat

Useful when you don’t know the number of iterations in advance (e.g., iteratively refining a design until convergence).

2.3 break and continue

  • break – immediately exits the loop, skipping all remaining iterations.
  • continue – skips the rest of the current iteration and moves to the next.

AEC analogy:

  • break like stopping the analysis once a critical failure is found.
  • continue like skipping a floor that has no structural elements to check.

3. Code Examples

Example 1: Summing loads on a beam (list of point loads)

# Point loads on a beam (kN) at various positions
point_loads = [45.0, 32.5, 28.0, 60.0]   # kN

total_load = 0.0
for load in point_loads:
    total_load += load   # same as total_load = total_load + load

print(f"Total point load on beam: {total_load:.1f} kN")

Example 2: Generate floor levels with a for loop and range()

# Generate floor level elevations
ground_floor_level = 0.0
floor_height = 3.5          # m per storey
num_floors = 8

print("Floor levels (m):")
for floor_num in range(1, num_floors + 1):
    level = ground_floor_level + floor_num * floor_height
    print(f"  Floor {floor_num}: {level:.2f} m")

Example 3: while loop – iterative beam depth selection

# Simple iterative selection of beam depth (illustrative)
depth = 200   # mm initial guess
required_depth = 450

while depth < required_depth:
    depth += 50
    print(f"Trying depth: {depth} mm")
print(f"Selected depth: {depth} mm")

Example 4: break – Stop checking after first failure

# Check a list of beam spans against a stock length
spans = [4.5, 6.2, 3.0, 8.1, 5.0]
stock = 6.0

for span in spans:
    if span > stock:
        print(f"FAIL: Span {span}m exceeds stock. Stopping order.")
        break
    else:
        print(f"OK: Span {span}m fits.")

Example 5: continue – Skip floors that are mechanical penthouses

# Process only occupied floors
floors = ["Lobby", "Office", "Office", "MEP", "Office", "Roof"]

for floor_name in floors:
    if floor_name == "MEP" or floor_name == "Roof":
        continue
    print(f"Designing ceiling grid for {floor_name}")

4. Hands‑on Exercises (3–5 Problems)

Problem 1 – Total floor area of a multi‑storey building
Each floor has the same rectangular plan: length = 25 m, width = 18 m.
There are 12 floors. Use a for loop with range() to sum the total area. Print the result.

Problem 2 – Check all columns in a list
Given a list of column loads (kN):
column_loads = [850, 920, 780, 1100, 650, 950]
A column’s capacity is 1000 kN. Loop through the list.

  • If a load exceeds capacity, print "Column X OVERLOADED" and break (stop checking further).
  • If all are safe, print "All columns OK".
    Use an else clause on the for loop (optional).

Problem 3 – Find the first beam that satisfies criteria
Given beam depths: [250, 300, 350, 400, 450, 500] (mm).
The minimum required depth is 320 mm. Loop until you find the first depth >= 320, print it and break.

Problem 4 – Generate a coordinate grid of columns
Use nested for loops (one loop inside another) to generate the coordinates of a 3×4 column grid.
Column spacing: X direction = 6 m, Y direction = 8 m.
Start at (0,0). Print each point as "Column at (x, y)".

Solutions (attempt first):

# P1
length = 25; width = 18
total_area = 0
for floor in range(12):
    total_area += length * width
print(f"Total floor area: {total_area} m²")

# P2
column_loads = [850, 920, 780, 1100, 650, 950]
capacity = 1000
for i, load in enumerate(column_loads):
    if load > capacity:
        print(f"Column {i+1} OVERLOADED")
        break
else:
    print("All columns OK")

# P3
depths = [250, 300, 350, 400, 450, 500]
required = 320
for d in depths:
    if d >= required:
        print(f"Selected depth: {d} mm")
        break

# P4
x_spacing = 6; y_spacing = 8
for row in range(3):       # row index 0..2
    for col in range(4):   # col index 0..3
        x = col * x_spacing
        y = row * y_spacing
        print(f"Column at ({x}, {y})")

5. Applied Challenge Task

Task: Automated Beam Summary Report

You are given the following data for a building’s floor beams:

beam_data = [
    {"mark": "B1", "span": 6.0, "load": 25},
    {"mark": "B2", "span": 4.5, "load": 18},
    {"mark": "B3", "span": 7.2, "load": 30},
    {"mark": "B4", "span": 5.0, "load": 22},
    {"mark": "B5", "span": 8.0, "load": 35},
]

Write a script that loops through beam_data and for each beam:

  1. Compute the maximum moment: M = (load * span**2) / 8 (simply supported, UDL in kN/m).
  2. Compute the required section modulus: S_req = M * 1000 / 250 (assuming 250 MPa steel, units: M in kNm → Nmm).
  3. If span > 7.0, print a warning: "Beam {mark}: span exceeds 7.0m – consider deeper section".
  4. After processing all beams, print the total steel weight (assume each beam weighs 80 kg/m of span) and the average moment.

This challenges you to combine loops, conditionals, and arithmetic – a realistic design‑office task.


6. Brief Review Summary

  • for loops iterate over sequences; range() is your friend for numeric loops.
  • while loops repeat until a condition changes – beware of infinite loops.
  • break exits the loop early; continue skips to the next iteration.
  • Loops enable processing of lists of building elements (beams, columns, floors) automatically.

Key takeaway:
Loops turn repetitive manual calculations into automated workflows. With Day 4, you can now handle entire sets of structural members in one script.


7. Preview of Next Topic (Day 5)

Tomorrow we’ll explore Functions, Scope, and Docstrings.
You’ll learn:

  • How to define reusable functions (e.g., def moment(load, span):).
  • The concept of scope (local vs. global variables).
  • Writing docstrings to document your engineering functions.
  • Building a small library of AEC functions (moment of inertia, section modulus, U‑value check).

Functions make your code organised, testable, and shareable – essential for professional practice.

Comments

EARN AT THE COMFORT OF YOUR HOME

Sponsored content

Popular posts from this blog

Day 5 – Functions, Scope, and Docstrings

Day 10 – Exception Handling and Debugging

Day 1 – Python Foundations for AEC Professionals