Lab 03: Control Flow, Loops, and Pseudocode#

1. Demonstration#

In this lab, you will learn:

  • Writing pseudocode to plan your programs

  • Using if/elif/else statements for decision making

  • Using for and while loops for iteration

  • Using for-else and while-else constructs

  • Writing clear comments to document your code

1.1 Example 1: Reactor Safety Classification#

Problem: Given a reactor temperature, classify the operating condition as:

  • “Safe” if T < 400 K

  • “Warning” if 400 ≤ T < 500 K

  • “Danger” if T ≥ 500 K

Pseudocode:

INPUT: temperature T
IF T < 400:
    OUTPUT "Safe"
ELSE IF T < 500:
    OUTPUT "Warning"
ELSE:
    OUTPUT "Danger"
# Example 1: If/elif/else statement

T = 456
# Check if temperature is in safe range
# Test the function with different temperatures
temperatures = [350, 450, 520, 298, 500]

print("Reactor Temperature Classification")
print("=" * 40)
Reactor Temperature Classification
========================================

1.2 Example 2: For Loop - Calculating Conversion#

Problem: A batch reactor achieves conversion X at different times. Calculate conversion at t = 0, 5, 10, 15, 20 minutes using:

\[ X(t) = 1 - e^{-kt} \]

where k = 0.05 min⁻¹

Pseudocode:

SET k = 0.05
SET times = [0, 5, 10, 15, 20]
FOR each time t in times:
    CALCULATE X = 1 - exp(-k*t)
    OUTPUT t and X
END FOR
# Example 2: For loop with list iteration

# Rate constant (min^-1)
k = 0.05

# Time points (minutes)
times = [0, 5, 10, 15, 20]

print("Batch Reactor Conversion vs. Time")
print("=" * 40)
print(f"{'Time (min)':<15} {'Conversion':<15}")
print("-" * 40)
Batch Reactor Conversion vs. Time
========================================
Time (min)      Conversion     
----------------------------------------

1.3 Example 3: While Loop - Iterative Calculation#

Problem: Calculate the number of iterations needed for a reactor to reach 95% conversion when X increases by 5% each iteration.

Pseudocode:

SET X = 0
SET target = 0.95
SET iterations = 0
WHILE X < target:
    INCREMENT X by 0.05
    INCREMENT iterations by 1
    OUTPUT current X and iterations
END WHILE
OUTPUT "Target reached in [iterations] iterations"
# Example 3: While loop

# Initialize conversion and target
X = 0.0
target_conversion = 0.95
iterations = 0

print("Iterative Conversion Calculation")
print("=" * 40)
print(f"Target conversion: {target_conversion}")
print()

# Continue looping while conversion is below target
Iterative Conversion Calculation
========================================
Target conversion: 0.95

1.4 Example 4: Using break - Emergency Shutdown#

Problem: Monitor reactor pressure readings and trigger an emergency shutdown if pressure exceeds 80 psi. Stop monitoring immediately when the critical threshold is reached.

Pseudocode:

SET pressure_readings = [45, 52, 58, 63, 71, 78, 85, 92]
SET critical_pressure = 80
FOR each reading in pressure_readings:
    OUTPUT current reading
    IF reading >= critical_pressure:
        OUTPUT "CRITICAL - Emergency shutdown!"
        BREAK
    END IF
END FOR
OUTPUT "Monitoring stopped"
# Example 4: Using break to exit a loop early

# Simulated pressure readings from reactor (psi)
pressure_readings = [45, 52, 58, 63, 71, 78, 85, 92]

# Safety threshold (psi)
critical_pressure = 80

print("Reactor Pressure Monitoring System")
print("=" * 45)
print(f"Critical threshold: {critical_pressure} psi\n")

# Monitor each pressure reading
Reactor Pressure Monitoring System
=============================================
Critical threshold: 80 psi

2. Practice Problems#

Now it’s your turn! Complete the following problems using control statements, loops, pseudocode, and comments.

Problem 1: For-Else Loop - Finding Valid Operating Condition#

Problem: Search for the first temperature that gives a reaction rate > 10 mol/(L·s). If not found, use a default.

Pseudocode:

SET temperatures = [300, 350, 400, 450, 500]
SET target_rate = 10
FOR each T in temperatures:
    CALCULATE rate using Arrhenius equation
    IF rate > target_rate:
        OUTPUT "Found valid T"
        BREAK
    END IF
ELSE:
    OUTPUT "No valid temperature found, using default"
END FOR-ELSE

The else clause executes only if the loop completes without hitting break.

# Problem 1

# Arrhenius parameters
A = 1e8  # Pre-exponential factor (L/(mol·s))
Ea = 50000  # Activation energy (J/mol)
R = 8.314  # Gas constant (J/(mol·K))

# Test temperatures (K)
temperatures = [300, 350, 400, 450, 500]
target_rate = 10  # Target rate (mol/(L·s))

print("Searching for Valid Operating Temperature")
print("=" * 50)

# Search for temperature that meets criterion
Searching for Valid Operating Temperature
==================================================

Problem 2: pH Classification#

Write a program that classifies solutions based on their pH values:

  • “Strongly Acidic” if pH < 3

  • “Weakly Acidic” if 3 ≤ pH < 7

  • “Neutral” if pH = 7

  • “Weakly Basic” if 7 < pH ≤ 11

  • “Strongly Basic” if pH > 11

Tasks:

  1. Write pseudocode for the classification logic

  2. Test with pH values: [1.5, 4.2, 7.0, 9.8, 13.0] using a for loop. Print results in a formatted table.

# Task 1
# Task 2
# List of pH values to test
pH_values = [1.5, 4.2, 7.0, 9.8, 13.0]

# Print table header
print("pH Classification Results")
print("=" * 40)
print(f"{'pH Value':<15} {'Classification':<20}")
print("-" * 40)
pH Classification Results
========================================
pH Value        Classification      
----------------------------------------

Problem 3: For-Else Loop - Finding Optimal Catalyst#

You are testing different catalysts to find one that gives a selectivity > 0.85. Test the following catalysts with their selectivities:

Catalyst

Selectivity

Pt/Al₂O₃

0.72

Pd/C

0.81

Ni/SiO₂

0.89

Cu/ZnO

0.65

Tasks:

  1. Write pseudocode using a for-else structure

  2. Store the data in a dictionary: catalysts = {"Pt/Al2O3": 0.72, "Pd/C": 0.81, ...}

  3. Use a for loop to search for a catalyst with selectivity > 0.85. When found, print the catalyst name and break the loop. Use the else clause to print “No suitable catalyst found” if none meet the criterion. Add descriptive comments throughout your code

Hint: You can loop through a dictionary using:

for name, selectivity in catalysts.items():
    # your code here
# Problem 2: Finding Optimal Catalyst
# Task 1
# Task 2

# Store catalyst data in a dictionary
catalysts = {
    "Pt/Al2O3": 0.72,
    "Pd/C": 0.81,
    "Ni/SiO2": 0.89,
    "Cu/ZnO": 0.65
}

# Task 3
# Target selectivity threshold
target_selectivity = 0.85

# Print header
print("Catalyst Screening for Selectivity > 0.85")
print("=" * 50)
Catalyst Screening for Selectivity > 0.85
==================================================