Advanced Loop Control#

In the Loops section, you learnt how to use for loops to iterate over sequences. In the Comparisons and Flow Control section, you learnt how to use if statements to make decisions in your code. Now we’ll combine these concepts and introduce some more advanced loop control structures.

This section covers:

  • while loops: loops that continue until a condition is no longer true

  • break: exiting a loop early

  • continue: skipping to the next iteration of a loop

These tools are particularly useful in computational chemistry for iterative algorithms that need to run until convergence, or for processing datasets where you need to skip invalid data or stop when certain conditions are met.

Prerequisites: Before working through this section, make sure you’re comfortable with:

while loops#

In addition to for loops, Python also provides while loops for situations where you want to repeat a block of code as long as a condition is true.

A while loop is particularly useful when you don’t know in advance how many iterations you’ll need - you just know when to stop.

Example: Cooling to Room Temperature#

Imagine a hot beaker cooling down to room temperature. The beaker loses 10% of the temperature difference with its surroundings in each time step. We want to simulate this cooling process until the beaker is within 0.5°C of room temperature.

temperature = 100.0  # Starting temperature in °C
room_temperature = 20.0  # Ambient temperature in °C
threshold = 0.5  # Stop when within 0.5°C of room temp
iteration = 0

while temperature - room_temperature > threshold:
    # Cool by 10% of the temperature difference each step
    temperature_difference = temperature - room_temperature
    temperature = temperature - 0.1 * temperature_difference
    iteration += 1
    print(f"Step {iteration}: Temperature = {temperature:.2f}°C")

print(f"Thermal equilibrium reached after {iteration} steps")
print(f"Final temperature: {temperature:.2f}°C")
Step 1: Temperature = 92.00°C
Step 2: Temperature = 84.80°C
Step 3: Temperature = 78.32°C
Step 4: Temperature = 72.49°C
Step 5: Temperature = 67.24°C
Step 6: Temperature = 62.52°C
Step 7: Temperature = 58.26°C
Step 8: Temperature = 54.44°C
Step 9: Temperature = 50.99°C
Step 10: Temperature = 47.89°C
Step 11: Temperature = 45.10°C
Step 12: Temperature = 42.59°C
Step 13: Temperature = 40.33°C
Step 14: Temperature = 38.30°C
Step 15: Temperature = 36.47°C
Step 16: Temperature = 34.82°C
Step 17: Temperature = 33.34°C
Step 18: Temperature = 32.01°C
Step 19: Temperature = 30.81°C
Step 20: Temperature = 29.73°C
Step 21: Temperature = 28.75°C
Step 22: Temperature = 27.88°C
Step 23: Temperature = 27.09°C
Step 24: Temperature = 26.38°C
Step 25: Temperature = 25.74°C
Step 26: Temperature = 25.17°C
Step 27: Temperature = 24.65°C
Step 28: Temperature = 24.19°C
Step 29: Temperature = 23.77°C
Step 30: Temperature = 23.39°C
Step 31: Temperature = 23.05°C
Step 32: Temperature = 22.75°C
Step 33: Temperature = 22.47°C
Step 34: Temperature = 22.23°C
Step 35: Temperature = 22.00°C
Step 36: Temperature = 21.80°C
Step 37: Temperature = 21.62°C
Step 38: Temperature = 21.46°C
Step 39: Temperature = 21.31°C
Step 40: Temperature = 21.18°C
Step 41: Temperature = 21.06°C
Step 42: Temperature = 20.96°C
Step 43: Temperature = 20.86°C
Step 44: Temperature = 20.78°C
Step 45: Temperature = 20.70°C
Step 46: Temperature = 20.63°C
Step 47: Temperature = 20.57°C
Step 48: Temperature = 20.51°C
Step 49: Temperature = 20.46°C
Thermal equilibrium reached after 49 steps
Final temperature: 20.46°C

How this works:

  • The while loop continues as long as the temperature is more than 0.5°C away from room temperature

  • Each iteration, the beaker cools by 10% of the current temperature difference

  • The loop automatically stops when the temperature gets close enough to room temperature

Key concept: With a while loop, we don’t need to know in advance how many iterations it will take - the loop continues until the condition becomes False.

continue and break#

Python provides additional flow control statements for controlling the behaviour of loops. For example, if a certain condition is met, we might want to jump straight to the next iteration of a loop without running the rest of the current code block, or we might want to quit the loop altogether.

  • continue → jump straight to the next iteration of the loop.

  • break → jump out of the loop entirely.

For example, if we are iterating through the numbers 0 to 99, but want to stop if we reach 3, we can use the break keyword:

for i in range(100):
    print(i)
    if i == 3:
        break
print('Loop exited')
0
1
2
3
Loop exited

Alternatively we might want to count numbers but skip those divisible by 3.

for i in range(20):
    if i%3 == 0: # `True` if i is divisible by 3
        continue
    print(i)
1
2
4
5
7
8
10
11
13
14
16
17
19

Exercises#

Exercise 1: Temperature-Dependent Reaction Rate Study#

Problem: You are investigating how reaction rate changes with temperature. Your automated system heats a reaction vessel from 20°C to 100°C in 8°C increments, taking a measurement at each temperature.

Write a while loop that:

  • Starts with temperature = 20 (°C)

  • Takes a measurement (just print the temperature for now)

  • Increases temperature by 8°C

  • Continues until temperature reaches or exceeds 100°C

Print each measurement temperature and count the total number of measurements taken.

Expected output format:

Measurement 1: 20°C
Measurement 2: 28°C
Measurement 3: 36°C
...
Completed X measurements from 20°C to Y°C

Exercise 2: Convergence with Iteration Limit#

Problem: The cooling simulation from the example converges relatively quickly because it loses 10% of the temperature difference each step. However, if the cooling rate is slower, convergence can take many iterations.

Modify the simulation to use a slower cooling rate (only 2% per step instead of 10%). This is more realistic for a well-insulated vessel. However, since convergence is now much slower, add an iteration limit of 100 steps. If equilibrium isn’t reached within 100 steps, stop and report that more time is needed.

Starting code:

temperature = 100.0  # Starting temperature in °C
room_temperature = 20.0  # Ambient temperature in °C
threshold = 0.5  # Stop when within 0.5°C of room temp
cooling_rate = 0.02  # Cool by 2% per step
iteration = 0
max_iterations = 100

while temperature - room_temperature > threshold:
    # Cool by 2% of the temperature difference each step
    temperature_difference = temperature - room_temperature
    temperature = temperature - cooling_rate * temperature_difference
    iteration += 1
    print(f"Step {iteration}: Temperature = {temperature:.2f}°C")

print(f"Thermal equilibrium reached after {iteration} steps")