Understanding Loops in Python
In this lab, you will learn about loops in Python, which are essential for performing repetitive tasks. You can perform the exercises in any of the following environments:
- Visual Studio Code (VS Code)
- Google Colab
- Jupyter Notebook
- PyCharm
- Anaconda
Setup Instructions
1. Visual Studio Code (VS Code)
- Installation: Ensure Python is installed and the Python extension is added to VS Code.
- Create a New File: Open VS Code and create a new Python file (e.g.,
loops_lab.py
). - Run the Code: Use the terminal or the run button in the editor to execute your code.
2. Google Colab
- Access Colab: Go to Google Colab.
- Create a New Notebook: Click on “New Notebook.”
- Run Cells: Write your code in a cell and run it by clicking the play button.
3. Jupyter Notebook
- Installation: Install Jupyter Notebook via Anaconda or pip.
- Start Jupyter: Open your terminal and type
jupyter notebook
to launch. - Create a New Notebook: Create a new Python notebook and write your code in the cells.
4. PyCharm
- Installation: Download and install PyCharm.
- Create a New Project: Start a new project and create a new Python file.
- Run the Code: Write your code and run it using the built-in run configuration.
5. Anaconda
- Launch Anaconda Navigator: Open Anaconda Navigator.
- Choose an Environment: Launch either Jupyter Notebook or Spyder.
- Create a New File/Notebook: Write your code in a new notebook or script.
Exercises
Exercise 1: For Loop
Task:
- Use a
for
loop to print the first 10 positive integers.
Example Code:
# Print the first 10 positive integers using a for loop
for i in range(1, 11):
print(i)
Exercise 2: While Loop
Task:
- Use a
while
loop to print numbers from 1 to 10.
Example Code:
# Print numbers from 1 to 10 using a while loop
number = 1
while number <= 10:
print(number)
number += 1
Exercise 3: Looping Through a List
Task:
- Create a list of fruits and use a
for
loop to print each fruit.
Example Code:
# List of fruits
fruits = ["apple", "banana", "cherry", "date"]
# Print each fruit using a for loop
for fruit in fruits:
print(fruit)
Exercise 4: Nested Loops
Task:
- Use nested loops to print a multiplication table (1 to 5).
Example Code:
# Print a multiplication table using nested loops
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i * j}")
print() # Print a new line after each row
Exercise 5: Break and Continue
Task:
- Use a loop to print numbers from 1 to 10, but skip the number 5 using
continue
and stop the loop if the number 8 is reached usingbreak
.
Example Code:
# Print numbers from 1 to 10, skipping 5 and stopping at 8
for i in range(1, 11):
if i == 5:
continue # Skip the number 5
if i == 8:
break # Stop the loop at 8
print(i)
Running the Code
- Copy the Code: Copy the code examples provided above into your Python file.
- Run the Program: Execute the program in your IDE. You can usually do this by clicking a “Run” button or using a keyboard shortcut (like
Shift + F10
in PyCharm). - Interact with the Program: Follow the prompts in the console to input your data if applicable.
Conclusion
This lab helps you understand loops in Python, including for
loops, while
loops, nested loops, and control statements like break
and continue
. By completing these exercises, you will gain practical experience in using loops to perform repetitive tasks efficiently.
or
Lab 06: Understanding Loops in Python (Civil Engineering Focus)
Objective: Use for
and while
loops to automate repetitive tasks in civil engineering, such as structural analysis, material testing, and construction scheduling.
Key Concepts
- Loop Types:
for
Loops: Iterate over sequences (e.g., lists, ranges) for tasks like batch processing.while
Loops: Repeat until a condition is met (e.g., convergence in iterative calculations).
- Civil Engineering Applications:
- Analyze multiple load cases.
- Process time-series sensor data.
- Simulate construction phases.
Task 1: Batch Processing Beam Deflections
Problem: Calculate deflections for multiple beams using a for
loop.
Formula:
[
\delta = \frac {5 \cdot w \cdot L^4}{384 \cdot E \cdot I}
]
Sample Input:
Number of beams: 3
Beam 1: w=8 kN/m, L=5 m, E=200 GPa, I=0.0002 m⁴
Beam 2: w=12 kN/m, L=6 m, E=200 GPa, I=0.0003 m⁴
Beam 3: w=10 kN/m, L=4 m, E=200 GPa, I=0.00015 m⁴
Sample Output:
Beam 1 Deflection: 10.42 mm
Beam 2 Deflection: 12.96 mm
Beam 3 Deflection: 29.63 mm
Solution Code:
num_beams = int(input("Number of beams: "))
for i in range(num_beams):
print(f"\nBeam {i+1}:")
w = float(input("Distributed load (kN/m): "))
L = float(input("Span length (m): "))
E = float(input("Modulus of elasticity (GPa): ")) * 1e9 # Convert to Pa
I = float(input("Moment of inertia (m⁴): "))
delta = (5 * w * 1000 * L**4) / (384 * E * I)
print(f"Deflection: {delta * 1000:.2f} mm")
Task 2: Soil Settlement Simulation with while
Loop
Problem: Simulate soil settlement until it stabilizes (< 1 mm change/day).
Formula:
[
\text{Settlement} = \text{Initial Settlement} \times e^{-kt}
]
where (k = 0.1) (decay constant).
Sample Output:
Day 1: Settlement = 50.00 mm
Day 2: Settlement = 45.00 mm
...
Day 29: Settlement = 1.94 mm
Day 30: Settlement = 1.75 mm
Settlement stabilized after 30 days.
Solution Code:
settlement = 50.0 # Initial settlement (mm)
k = 0.1
day = 0
threshold = 1.0 # Stabilization threshold (mm/day)
while True:
day += 1
prev_settlement = settlement
settlement *= 0.9 # Simplified decay model: e^(-kt) ≈ 0.9 per day
change = prev_settlement - settlement
print(f"Day {day}: Settlement = {settlement:.2f} mm")
if abs(change) < threshold:
print(f"Settlement stabilized after {day} days.")
break
Task 3: Construction Schedule with Nested Loops
Problem: Calculate total duration and cost for a multi-phase construction project.
Sample Input:
Number of phases: 2
Phase 1: 3 tasks, each taking 5 days, cost $2000/task
Phase 2: 4 tasks, each taking 7 days, cost $3000/task
Sample Output:
Phase 1: 15 days, $6000
Phase 2: 28 days, $12000
Total: 43 days, $18000
Solution Code:
total_days = 0
total_cost = 0
phases = int(input("Number of phases: "))
for phase in range(1, phases + 1):
tasks = int(input(f"Phase {phase}: Number of tasks: "))
days_per_task = int(input("Days per task: "))
cost_per_task = float(input("Cost per task ($): "))
phase_days = tasks * days_per_task
phase_cost = tasks * cost_per_task
total_days += phase_days
total_cost += phase_cost
print(f"Phase {phase}: {phase_days} days, ${phase_cost:.0f}")
print(f"\nTotal: {total_days} days, ${total_cost:.0f}")
Task 4: Traffic Flow Analysis with List Comprehensions
Problem: Process hourly traffic counts to find peak hours (volume > 100 vehicles).
Sample Input:
Hourly counts: [85, 120, 95, 150, 80, 130]
Sample Output:
Peak hours: 7:00 (120), 9:00 (150), 11:00 (130)
Solution Code:
counts = [85, 120, 95, 150, 80, 130]
peak_hours = [f"{7 + i}:00 ({count})"
for i, count in enumerate(counts)
if count > 100]
print("Peak hours:", ", ".join(peak_hours))
Key Takeaways
- Automation: Use
for
loops to process batches (e.g., beams, tasks). - Convergence:
while
loops for iterative simulations (e.g., settlement, stability). - Efficiency: List comprehensions simplify data filtering/transformation.
Challenge Problem
Problem: Track construction progress until completion. Each day, 5% of the remaining work is completed.
Sample Input:
Total work (e.g., 100%): 100
Sample Output:
Day 1: 5.00% completed, 95.00% remaining
Day 2: 9.75% completed, 90.25% remaining
...
Day 59: 95.26% completed, 4.74% remaining
Day 60: 95.50% completed, 4.50% remaining
Project completed after 60 days.
Solution Snippet:
total = 100.0 # Total work (%)
remaining = total
day = 0
while remaining > 0.1: # Stop when < 0.1% remaining
day += 1
completed = total - remaining
remaining *= 0.95 # 5% progress daily
print(f"Day {day}: {completed:.2f}% completed, {remaining:.2f}% remaining")
print(f"Project completed after {day} days.")