🔄 Python Training - Day 2

Control Flow, Loops, Conditionals & Iteration

Python version: 3.12+ (verify with python --version)

📊 Quick Comparison

Construct Purpose Example
if / elif / else Branch logic if x > 0: ...
for Iterate sequence for n in items:
while Loop while condition while ok:
break Exit loop break
continue Skip iteration continue

📝 Quick Quiz (5 Questions)

  1. Which statement exits a loop immediately?
  2. Which loop runs while a condition is true?
  3. Choose a boolean operator:
  4. What does continue do?
  5. Which branch handles multiple conditions?
Answer all questions and click Submit.

🎯 Conditionals

Boolean Values and Operators

Boolean values in Python are True and False. Boolean operators include and, or, and not.

Conditional (if)

Executes a block of code if a condition is true.

# Check if switch is active is_active = True if is_active: print("Switch is operational")

Alternative (if-else)

Executes one block if true, another if false.

# Toggle switch status if is_active: print("Switch is active") else: print("Switch is inactive")

Chained Conditional (if-elif-else)

Allows multiple conditions to be checked in sequence.

# Configure VLAN based on priority priority = 2 if priority == 1: print("High priority VLAN") elif priority == 2: print("Medium priority VLAN") else: print("Low priority VLAN")

🔄 Iteration

While Loop

Executes as long as a condition is true.

# Monitor switches switch_count = 0 while switch_count < 3: print(f"Monitoring switch {switch_count + 1}") switch_count += 1

For Loop

Iterates over a sequence (list, tuple, string).

# Display switch information switches = ["SW101", "SW102", "SW110"] for switch in switches: print(f"Checking status of {switch}")

Break Statement

Exits a loop immediately.

# Find first active switch switches = ["SW101", "SW102", "SW110"] for switch in switches: if switch == "SW102": print(f"Found active switch: {switch}") break

Continue Statement

Skips the rest of the code and jumps to the next iteration.

# List only active switches switches = ["SW101", "SW102", "SW110"] for switch in switches: if switch == "SW101": continue # Skip SW101 print(f"Active switch: {switch}")

🎮 Interactive Demo: Control Flow Practice

Try different control flow patterns:

Conditional Demo

Enter a switch name to check its status!

Loop Demo

Enter a number to see the loop in action!

🧩 Source Code: Control Flow Practice

HTML for the demo UI:

<div class="interactive-demo">
    <h3>Try different control flow patterns:</h3>
    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
        <div>
            <h4>Conditional Demo</h4>
            <input type="text" class="demo-input" id="switchName" placeholder="Enter switch name (SW101, SW102, SW110)">
            <button class="demo-button" onclick="checkSwitch()">Check Switch</button>
            <div class="output" id="conditionalOutput">Enter a switch name to check its status!</div>
        </div>
        <div>
            <h4>Loop Demo</h4>
            <input type="number" class="demo-input" id="loopCount" placeholder="Enter number of iterations (1-10)" min="1" max="10">
            <button class="demo-button secondary" onclick="runLoop()">Run Loop</button>
            <div class="output" id="loopOutput">Enter a number to see the loop in action!</div>
        </div>
    </div>
</div>

JavaScript for the demo logic:

function checkSwitch() {
    const switchName = document.getElementById('switchName').value;
    const output = document.getElementById('conditionalOutput');
    
    if (switchName === '') {
        output.textContent = 'Please enter a switch name!';
        return;
    }
    
    const activeSwitches = ['SW101', 'SW102', 'SW110'];
    if (activeSwitches.includes(switchName)) {
        output.textContent = `Switch: ${switchName}\nStatus: Active\nPorts: 48\nUptime: 99.9%`;
    } else {
        output.textContent = `Switch: ${switchName}\nStatus: Not Found\nError: Switch does not exist in topology`;
    }
}

function runLoop() {
    const count = parseInt(document.getElementById('loopCount').value);
    const output = document.getElementById('loopOutput');
    
    if (isNaN(count) || count < 1 || count > 10) {
        output.textContent = 'Please enter a valid number between 1 and 10!';
        return;
    }
    
    let result = `Running loop for ${count} iterations:\n\n`;
    for (let i = 0; i < count; i++) {
        result += `Iteration ${i + 1}: Checking switches...\n`;
        result += `  - SW101: Active\n`;
        result += `  - SW102: Active\n`;
        result += `  - SW110: Active\n\n`;
    }
    result += 'Loop completed!';
    
    output.textContent = result;
}

🌐 Network Topology Examples

Let's consider a network topology where we need to perform various tasks using control flow statements and loops.

Example Topology

SW101
↔
SW102
↔
SW110

Complete Network Management Script

def check_switch_status(switch_name): """Check if a switch is active""" active_switches = ["SW101", "SW102", "SW110"] if switch_name in active_switches: print(f"{switch_name} is active") return True else: print(f"{switch_name} is not found") return False def toggle_switch_status(switch_name, current_status): """Toggle switch status between active and inactive""" if current_status: print(f"{switch_name} is now inactive") return False else: print(f"{switch_name} is now active") return True def configure_vlan(switch_name, vlan_id, vlan_name): """Configure VLAN on a switch""" if switch_name == "SW101": print(f"Configuring VLAN {vlan_id} ({vlan_name}) on {switch_name}") return True elif switch_name == "SW102": print(f"Configuring VLAN {vlan_id} ({vlan_name}) on {switch_name}") return True elif switch_name == "SW110": print(f"Configuring VLAN {vlan_id} ({vlan_name}) on {switch_name}") return True else: print(f"Switch {switch_name} not found") return False def monitor_switches(iterations): """Monitor switches for a set number of iterations""" switches = ["SW101", "SW102", "SW110"] count = 0 while count < iterations: print(f"\\n--- Monitoring Cycle {count + 1} ---") for switch in switches: print(f"Checking {switch}...") count += 1 def display_switch_info(): """Display information about all switches""" switches = ["SW101", "SW102", "SW110"] for switch in switches: print(f"Switch: {switch}") print(f" Status: Active") print(f" Ports: 48") print(f" Uptime: 99.9%") def find_first_active_switch(): """Find and print the first active switch""" switches = ["SW101", "SW102", "SW110"] for switch in switches: if switch.startswith("SW"): print(f"First active switch found: {switch}") break def list_active_switches(): """List all active switches, skipping inactive ones""" switches = ["SW101", "SW102", "SW110"] for switch in switches: if switch == "SW101": continue # Skip SW101 for this example print(f"Active switch: {switch}") # Example usage if __name__ == "__main__": print("=== Network Management System ===") # Test conditionals check_switch_status("SW101") check_switch_status("SW999") # Test loops monitor_switches(2) display_switch_info() find_first_active_switch() list_active_switches()

📊 Control Flow Summary

Conditional Statements:

  • if: Execute code when condition is true
  • if-else: Choose between two code paths
  • if-elif-else: Choose between multiple code paths

Loop Statements:

  • while: Repeat while condition is true
  • for: Iterate over a sequence
  • break: Exit loop immediately
  • continue: Skip to next iteration

Best Practices:

  • Use meaningful variable names
  • Keep conditions simple and readable
  • Avoid infinite loops
  • Use break and continue judiciously

🎮 Interactive Demo: Complete Network Script

Run the complete network management script:

Click "Run Network Script" to see the complete example in action!

▶️ Run the code (Python in your browser)

Execute Python below using Pyodide. Edit the code and click Run.

Initializing Python runtime...

🎥 Video Lesson

© NexIQ AI Automation Pvt Ltd | https://nexiq.netlify.app/ | hr@nexiq.in