šŸ Week 1: Python Foundations

Day 3: Conditions & Loops

Duration: 5 Hours

šŸ“š Learning Objectives

By the end of this session, you will be able to:

  • Write conditional statements with if, elif, else
  • Use comparison and logical operators
  • Create for loops to iterate over sequences
  • Use while loops for conditional iteration
  • Control loop flow with break and continue

šŸ“– Core Concepts (2 Hours)

Conditional Statements: if

Conditionals let your program make decisions based on conditions.

# Basic if statement age = 20 if age >= 18: print("You are an adult") # With else temperature = 35 if temperature > 30: print("It's hot!") else: print("It's comfortable") # DevOps example cpu_usage = 85 if cpu_usage > 80: print("āš ļø Warning: High CPU usage!") else: print("āœ“ CPU usage normal")

Multiple Conditions: elif

# elif = else if score = 75 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F" print(f"Your grade: {grade}") # DevOps: Server status check status_code = 503 if status_code == 200: print("āœ“ OK - Service running") elif status_code == 404: print("āœ— Not Found") elif status_code == 500: print("āœ— Internal Server Error") elif status_code == 503: print("āœ— Service Unavailable") else: print(f"Unknown status: {status_code}")

Comparison Operators

# Comparison operators return True or False x = 10 y = 5 print(x == y) # False (equal to) print(x != y) # True (not equal to) print(x > y) # True (greater than) print(x < y) # False (less than) print(x >= y) # True (greater or equal) print(x <= y) # False (less or equal) # String comparison name = "admin" if name == "admin": print("Welcome, administrator!") # Checking membership if "log" in "/var/log/syslog": print("This is a log file path")

Logical Operators

# and, or, not # and - both must be True age = 25 has_license = True if age >= 18 and has_license: print("You can drive") # or - at least one must be True day = "Saturday" if day == "Saturday" or day == "Sunday": print("It's the weekend!") # not - reverses the boolean is_maintenance = False if not is_maintenance: print("System is operational") # Complex conditions cpu = 70 memory = 85 disk = 90 if cpu > 80 or memory > 80 or disk > 80: print("āš ļø Resource alert!") if cpu < 80 and memory < 80 and disk < 80: print("āœ“ All resources OK")

Nested Conditions

# Conditions inside conditions user = "admin" password = "secret123" is_active = True if user == "admin": if password == "secret123": if is_active: print("Access granted!") else: print("Account disabled") else: print("Wrong password") else: print("User not found") # Cleaner with and if user == "admin" and password == "secret123" and is_active: print("Access granted!")

For Loops

# Iterate over a sequence # Loop through a list servers = ["web-01", "web-02", "db-01"] for server in servers: print(f"Checking {server}...") # Loop through a string for char in "Python": print(char) # Loop with range() for i in range(5): # 0, 1, 2, 3, 4 print(f"Iteration {i}") for i in range(1, 6): # 1, 2, 3, 4, 5 print(f"Server-{i}") for i in range(0, 10, 2): # 0, 2, 4, 6, 8 print(i) # Loop with index using enumerate() fruits = ["apple", "banana", "cherry"] for index, fruit in fruits: print(f"{index}: {fruit}")

While Loops

# Loop while condition is True # Basic while loop count = 0 while count < 5: print(f"Count: {count}") count += 1 # DevOps: Retry logic attempts = 0 max_attempts = 3 connected = False while attempts < max_attempts and not connected: attempts += 1 print(f"Connection attempt {attempts}...") # Simulate connection (would be real code) if attempts == 3: connected = True if connected: print("āœ“ Connected!") else: print("āœ— Failed to connect") # User input loop while True: response = input("Continue? (yes/no): ") if response.lower() == "no": print("Goodbye!") break

Break and Continue

# break - exit the loop immediately for i in range(10): if i == 5: print("Found 5, stopping!") break print(i) # Output: 0, 1, 2, 3, 4, Found 5, stopping! # continue - skip to next iteration for i in range(10): if i % 2 == 0: # Skip even numbers continue print(i) # Output: 1, 3, 5, 7, 9 # DevOps: Process only active servers servers = [ {"name": "web-01", "active": True}, {"name": "web-02", "active": False}, {"name": "db-01", "active": True}, ] for server in servers: if not server["active"]: continue print(f"Processing {server['name']}")

Loop with else

# else runs if loop completes without break # Search example numbers = [1, 3, 5, 7, 9] target = 4 for num in numbers: if num == target: print(f"Found {target}!") break else: print(f"{target} not found in list") # DevOps: Check all services services = ["nginx", "mysql", "redis"] for service in services: status = "running" # Would check actual status if status != "running": print(f"āœ— {service} is down!") break else: print("āœ“ All services running!")

šŸ”¬ Hands-on Lab (2.5 Hours)

Lab 1: Grade Calculator

  • Get a score from user input
  • Use if/elif/else for grade
  • Add pass/fail status
# Lab 1: grade_calculator.py print("=== Grade Calculator ===") score = int(input("Enter your score (0-100): ")) # Determine grade if score >= 90: grade = "A" status = "Excellent!" elif score >= 80: grade = "B" status = "Good job!" elif score >= 70: grade = "C" status = "Satisfactory" elif score >= 60: grade = "D" status = "Needs improvement" else: grade = "F" status = "Failed" # Pass/Fail passed = score >= 60 print() print(f"Score: {score}") print(f"Grade: {grade}") print(f"Status: {status}") print(f"Result: {'PASS' if passed else 'FAIL'}")

Lab 2: Number Guessing Game

  • Generate a random number
  • Use while loop for guesses
  • Provide hints (higher/lower)
# Lab 2: guessing_game.py import random print("=== Number Guessing Game ===") print("I'm thinking of a number between 1 and 100") print() secret = random.randint(1, 100) attempts = 0 max_attempts = 7 while attempts < max_attempts: guess = int(input("Your guess: ")) attempts += 1 if guess == secret: print(f"šŸŽ‰ Correct! You got it in {attempts} attempts!") break elif guess < secret: print("šŸ“ˆ Higher!") else: print("šŸ“‰ Lower!") remaining = max_attempts - attempts if remaining > 0: print(f" ({remaining} attempts remaining)") else: print(f"😢 Game over! The number was {secret}")

Lab 3: Server Health Monitor

  • Loop through server list
  • Check CPU, memory, disk
  • Alert on high usage
# Lab 3: health_monitor.py print("=" * 50) print(" SERVER HEALTH MONITOR") print("=" * 50) # Simulated server data servers = [ {"name": "web-01", "cpu": 45, "memory": 60, "disk": 70}, {"name": "web-02", "cpu": 85, "memory": 75, "disk": 65}, {"name": "db-01", "cpu": 30, "memory": 90, "disk": 85}, {"name": "cache-01", "cpu": 20, "memory": 40, "disk": 30}, ] # Thresholds CPU_THRESHOLD = 80 MEMORY_THRESHOLD = 80 DISK_THRESHOLD = 80 alerts = [] for server in servers: name = server["name"] print(f"\nChecking {name}...") # Check each metric if server["cpu"] > CPU_THRESHOLD: alert = f" āš ļø {name}: High CPU ({server['cpu']}%)" print(alert) alerts.append(alert) if server["memory"] > MEMORY_THRESHOLD: alert = f" āš ļø {name}: High Memory ({server['memory']}%)" print(alert) alerts.append(alert) if server["disk"] > DISK_THRESHOLD: alert = f" āš ļø {name}: High Disk ({server['disk']}%)" print(alert) alerts.append(alert) # All OK? if (server["cpu"] <= CPU_THRESHOLD and server["memory"] <= MEMORY_THRESHOLD and server["disk"] <= DISK_THRESHOLD): print(f" āœ“ {name}: All metrics OK") # Summary print("\n" + "=" * 50) print("SUMMARY") print("=" * 50) print(f"Servers checked: {len(servers)}") print(f"Alerts generated: {len(alerts)}") if alerts: print("\nAll Alerts:") for alert in alerts: print(alert) else: print("\nāœ“ No alerts - all systems healthy!")

Lab 4: Menu System

  • Create an interactive menu
  • Use while loop for persistence
  • Handle invalid choices
# Lab 4: menu_system.py def show_menu(): print("\n=== DevOps Tools Menu ===") print("1. Check server status") print("2. View logs") print("3. Deploy application") print("4. Backup database") print("5. Exit") print() while True: show_menu() choice = input("Select option (1-5): ") if choice == "1": print("\nšŸ“Š Checking server status...") print(" All servers operational!") elif choice == "2": print("\nšŸ“‹ Recent logs:") print(" [INFO] Application started") print(" [INFO] Connection established") print(" [WARN] High memory usage detected") elif choice == "3": confirm = input("\nāš ļø Deploy to production? (yes/no): ") if confirm.lower() == "yes": print("šŸš€ Deploying application...") print("āœ“ Deployment successful!") else: print("Deployment cancelled.") elif choice == "4": print("\nšŸ’¾ Starting backup...") for i in range(1, 4): print(f" Backing up table {i}/3...") print("āœ“ Backup complete!") elif choice == "5": print("\nGoodbye! šŸ‘‹") break else: print("\nāŒ Invalid option! Please choose 1-5.")

šŸ“ Practice Exercises

  1. Write a FizzBuzz program (1-100: Fizz for 3, Buzz for 5, FizzBuzz for both)
  2. Create a login system with 3 attempts maximum
  3. Build a multiplication table generator
  4. Write a program that finds prime numbers up to N

šŸ’” DevOps Relevance

Why this matters:

  • Conditions: Health checks, status validation, routing logic
  • For loops: Iterate servers, process logs, bulk operations
  • While loops: Retry logic, polling, waiting for conditions
  • Break/Continue: Error handling, skip inactive resources

āœ… Day 3 Checklist

  • Can write if/elif/else statements
  • Understand comparison operators
  • Can use logical operators (and, or, not)
  • Can create for loops with range()
  • Can create while loops
  • Know when to use break and continue