📓 Python Programming - Control Structures


1. Conditional Statements

Conditional Statements in Python: - Used to make decisions based on conditions.

  • Keywords: if, elif, else.
# Simple if-else
age = 20

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

# if-elif-else
marks = 85

if marks >= 90:
    print("Grade: A+")
elif marks >= 75:
    print("Grade: A")
elif marks >= 60:
    print("Grade: B")
else:
    print("Grade: C")

Nested Conditionals & Ternary Operator:

# Nested conditionals
age = 25
has_license = True

if age >= 18:
    if has_license:
        print("You can drive!")
    else:
        print("You need a license to drive.")
else:
    print("You're too young to drive.")

# Ternary operator (conditional expression)
result = "Pass" if marks >= 60 else "Fail"
print(f"Result: {result}")

# Multiple conditions with logical operators
temperature = 25
weather = "sunny"

if temperature > 20 and weather == "sunny":
    print("Perfect weather for outdoor activities!")
elif temperature > 20 or weather == "cloudy":
    print("Good weather for a walk.")
else:
    print("Stay indoors!")

2. Loops

Python supports two main types of loops: 1. for loop → Iterate over sequences (strings, lists, tuples, etc.)

  1. while loop → Repeats while a condition is True

➤ For Loop Example:

# Loop over a range of numbers - For loop example
for i in range(5):
    print(i)

Understanding range() and enumerate():

# Different ways to use range()
print("range(5):")
for i in range(5):
    print(i, end=" ")
print()

print("range(2, 8):")
for i in range(2, 8):
    print(i, end=" ")
print()

print("range(0, 10, 2):")
for i in range(0, 10, 2):
    print(i, end=" ")
print()

print("range(10, 0, -2):")
for i in range(10, 0, -2):
    print(i, end=" ")
print()

# Using enumerate() to get index and value
fruits = ["apple", "banana", "cherry", "date"]
print("\nUsing enumerate():")
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Starting enumerate from a different number
print("\nEnumerate starting from 1:")
for index, fruit in enumerate(fruits, 1):
    print(f"{index}. {fruit}")
# Loop over a list - For loop example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

➤ While Loop Example:

# Print numbers 1 to 5 using while loop
count = 1
while count <= 5:
    print(count)
    count += 1

While/Else Loop & Infinite Loop Prevention:

# While-else loop
count = 1
while count <= 3:
    print(f"Count: {count}")
    count += 1
else:
    print("Loop completed successfully!")

# Infinite loop prevention with safety counter
safety_counter = 0
MAX_ITERATIONS = 1000

while True:
    safety_counter += 1
    # Your loop logic here
    if safety_counter >= MAX_ITERATIONS:
        print("Safety break: Maximum iterations reached")
        break
    # Simulating some condition that would normally break the loop
    if safety_counter >= 5:
        print("Normal break condition met")
        break
    print(f"Iteration {safety_counter}")

# Common infinite loop mistake (commented to prevent actual infinite loop)
# x = 10
# while x > 0:
#     print(x)
#     # Forgot to decrement x - this would run forever!
# Print even numbers from 1 to 10 using while loop
count = 1
while count <= 10:
    if count % 2 == 0:
        print(count)
    count += 1

3. Looping Over Tuples, Strings, & Dictionaries

# Tuple
colors = ("red", "green", "blue")
for color in colors:
    print(color)

# String
for char in "Python":
    print(char)

# Dictionary
student = {"name": "Alice", "age": 21}
for key, value in student.items():
    print(f"{key}: {value}")

Advanced Looping Techniques:

# Using zip() to iterate over multiple sequences
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "London", "Tokyo"]

print("Using zip():")
for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")

# Using reversed() to iterate backwards
print("\nUsing reversed():")
for fruit in reversed(["apple", "banana", "cherry"]):
    print(fruit)

# List comprehensions (brief introduction)
print("\nList comprehensions:")
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(f"Squares: {squares}")

even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"Even squares: {even_squares}")

# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for row in matrix for item in row]
print(f"Flattened matrix: {flat_list}")

4. Special Loops: for/else

The else block after a for loop executes if the loop completes normally (no break).

# Check if a number is prime
num = 7
for i in range(2, num):
    if num % i == 0:
        print(f"{num} is not prime.")
        break
else:
    print(f"{num} is prime.")

5. Nested Loops and Flow Control

# Nested loop for multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("---")

6. Special Statements: pass, continue, break

# pass - placeholder
for i in range(3):
    pass  # Does nothing, placeholder for future code

print("=" * 5)
# continue - skip current iteration
for i in range(5):
    if i == 2:
        continue
    print(i)
print("=" * 5)
# break - exit loop
for i in range(5):
    if i == 3:
        break
    print(i)
print("=" * 5)

Error Handling in Loops:

# Handling errors in loops
numbers = ["1", "2", "three", "4", "5"]

print("Processing numbers with error handling:")
for num_str in numbers:
    try:
        num = int(num_str)
        print(f"Number: {num}, Square: {num**2}")
    except ValueError:
        print(f"'{num_str}' is not a valid number, skipping...")

# Using flags to control loop behavior
print("\nUsing flags:")
found = False
target = 3
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == target:
        print(f"Found {target}!")
        found = True
        break

if not found:
    print(f"{target} not found in the list")

# Breaking out of nested loops using functions
def find_in_matrix(matrix, target):
    for i, row in enumerate(matrix):
        for j, value in enumerate(row):
            if value == target:
                return i, j
    return None

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = find_in_matrix(matrix, 5)
if result:
    print(f"Found at position: {result}")
else:
    print("Not found")

7. Resolving Real-World Problems

Let's solve a simple real-world problem using control structures.

# Simple password validation
correct_password = "python123"
attempts = 3

while attempts > 0:
    pwd = input("Enter password: ")
    if pwd == correct_password:
        print("Access granted!")
        break
    else:
        print("Incorrect password. Try again.")
        attempts -= 1

if attempts == 0:
    print("Access denied. Too many failed attempts.")

8. Match/Case Statement (Python 3.10+)

The match/case statement is Python's version of switch-case from other languages.

# Basic match/case example
day = "Monday"

match day:
    case "Monday":
        print("Start of the work week!")
    case "Tuesday" | "Wednesday" | "Thursday":
        print("Midweek days")
    case "Friday":
        print("TGIF!")
    case "Saturday" | "Sunday":
        print("Weekend!")
    case _:
        print("Invalid day")

# Match with conditions
score = 85

match score:
    case x if x >= 90:
        grade = "A"
    case x if x >= 80:
        grade = "B"
    case x if x >= 70:
        grade = "C"
    case x if x >= 60:
        grade = "D"
    case _:
        grade = "F"

print(f"Score: {score}, Grade: {grade}")

# Match with data structures
def process_data(data):
    match data:
        case {"type": "user", "name": str(name)}:
            return f"Hello, {name}!"
        case {"type": "product", "name": str(name), "price": float(price)}:
            return f"Product: {name}, Price: ${price}"
        case list() if len(data) > 0:
            return f"List with {len(data)} items"
        case _:
            return "Unknown data format"

# Test the function
print(process_data({"type": "user", "name": "Alice"}))
print(process_data({"type": "product", "name": "Laptop", "price": 999.99}))
print(process_data([1, 2, 3, 4, 5]))

🛠️ AI Tool: Google Colab - Gemini Or Github Copilot

You can explore AI tools like Gemini inside Google Colab to assist with understanding Python code, generating examples, or debugging.

Example: - Use Google Colab's built-in chat assistant for hints or suggestions.

  • Explore AI code completion to speed up your coding.

  • Alternative: Github Copilot

🎯 Quick Recap

  • Use if, elif, else for decision-making

  • for and while loops help with repetition

  • Loop over sequences like tuples, strings, dictionaries

  • Special loop structures: for/else

  • Use pass, continue, break for flow control

  • Practice solving real-world problems

📝 Practice Exercises

Basic Exercises:

  1. Write a program that checks whether a number is positive, negative, or zero.

  2. Print all even numbers from 1 to 20 using a for loop.

  3. Create a simple calculator using if-elif-else.

  4. Write a program to validate password input with a maximum of 3 attempts.

Intermediate Exercises:

  1. Create a number guessing game where the computer picks a random number and the user has to guess it.

  2. Write a program that prints the multiplication table for any given number.

  3. Use nested loops to print patterns like triangles and diamonds.

  4. Create a menu-driven program using match/case (if available) or if-elif-else.

Advanced Exercises:

  1. Write a program that finds all prime numbers up to a given number using nested loops.

  2. Create a simple ATM system with balance checking, withdrawal, and deposit features.

  3. Build a word frequency counter that counts how many times each word appears in a sentence.

  4. Write a program that validates user input and keeps asking until valid data is entered.

Challenge Exercises:

  1. Create a simple text-based adventure game using control structures.

  2. Build a grade management system that can add, remove, and calculate average grades.

  3. Write a program that simulates a simple voting system with candidate validation.

  4. Create a loan eligibility checker based on multiple criteria (age, income, credit score).