Unit 2 • Lesson 11

Practical Control Flow Examples

Overview

Put everything together by building small interactive programs — from simple calculators to number-guessing games. This subtopic focuses on applying conditional logic and loops to solve real-world problems.

Beginner 30–40 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • Combining concepts: See how conditionals, loops, and control statements work together.
  • Building real programs: Create complete programs that solve practical problems.
  • Problem-solving approach: Learn how to break down problems and use control flow to solve them.
  • Reading and understanding code: Practice reading more complex programs that combine multiple concepts.

Why This Matters

Real programs combine multiple concepts together. In this lesson, you'll see how everything you've learned — conditionals, loops, variables, and more — work together to create useful programs. This is where you start thinking like a programmer, breaking problems into smaller pieces and using control flow to solve them.

Example 1: Simple Calculator

Let's build a simple calculator that performs basic arithmetic operations. This combines conditionals, user input, and variables.

Simple Calculator Program
# Get two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Get the operation
operation = input("Enter operation (+, -, *, /): ")

# Perform the calculation based on operation
if operation == "+":
    result = num1 + num2
elif operation == "-":
    result = num1 - num2
elif operation == "*":
    result = num1 * num2
elif operation == "/":
    if num2 != 0:
        result = num1 / num2
    else:
        result = "Error: Cannot divide by zero!"
else:
    result = "Invalid operation"

print(f"Result: {result}")

How This Works

This program first gets two numbers from the user and stores them in variables. Then it asks what operation to perform. Using if-elif-else statements, it checks which operation was chosen and performs the appropriate calculation. Notice how it handles division by zero — if the user tries to divide by zero, it prints an error message instead of crashing. This is a practical example of combining conditionals to handle different cases.

Try It: Simple Calculator

Try It Yourself

Note: Since we can't use input() interactively here, try modifying the code to use fixed values:

Press Run to see output

What happened? The code used if-elif-else statements to check which operation was chosen. Since operation was "+", Python entered the first if block and calculated num1 + num2, which equals 15. Try changing operation to "-", "*", or "/" to see different calculations. This demonstrates how conditionals let your program make decisions and perform different actions based on the input.

Example 2: Number Guessing Game

Let's create a simple number guessing game that combines loops and conditionals. The program picks a number and the user tries to guess it.

Number Guessing Game
# Secret number (in a real game, this would be random)
secret = 7
guess = None
attempts = 0

print("I'm thinking of a number between 1 and 10!")

while guess != secret:
    guess = int(input("Guess the number: "))
    attempts = attempts + 1
    
    if guess < secret:
        print("Too low! Try again.")
    elif guess > secret:
        print("Too high! Try again.")
    else:
        print(f"Correct! You guessed it in {attempts} attempts!")

How This Works

This program uses a while loop that keeps running until the user guesses correctly. Inside the loop, it gets a guess from the user and checks if it's too low, too high, or correct. If it's correct, the condition guess != secret becomes False and the loop stops. The program also tracks how many attempts the user made. This combines a while loop with nested conditionals to create an interactive game.

Try It: Simplified Guessing Game

Try It Yourself

Try a simplified version that checks guesses in a loop:

Press Run to see output

What happened? The program went through each guess in the list. For guess 3, it was less than 7 (the secret), so it printed "Too low!". For guess 5, it was still less than 7, so it printed "Too low!" again. For guess 7, it matched the secret number, so it printed "Correct!" and then executed break, which stopped the loop immediately (so guess 9 was never checked). This demonstrates combining a for loop with conditionals and break to create a game-like program!

Example 3: Counting and Filtering

Let's create a program that processes a list of numbers, counting how many are positive, negative, or zero, and filtering out certain values.

Counting and Filtering Numbers
numbers = [5, -3, 0, 12, -8, 7, 0, -1]
positive_count = 0
negative_count = 0
zero_count = 0
filtered_numbers = []

for num in numbers:
    if num > 0:
        positive_count = positive_count + 1
        filtered_numbers.append(num)
    elif num < 0:
        negative_count = negative_count + 1
    else:
        zero_count = zero_count + 1

print(f"Positive: {positive_count}")
print(f"Negative: {negative_count}")
print(f"Zero: {zero_count}")
print(f"Filtered (positive only): {filtered_numbers}")

How This Works

This program loops through each number in a list. For each number, it uses if-elif-else to categorize it as positive, negative, or zero, and increments the appropriate counter. It also adds positive numbers to a new list called filtered_numbers. This demonstrates how loops and conditionals work together to process data and extract information.

Try It: Count and Filter

Try It Yourself

Try this counting and filtering example:

Press Run to see output

What happened? The program went through each number in the list. For 5, it was positive, so it incremented positive_count and added 5 to filtered_numbers. For -3, it was negative, so it incremented negative_count. For 0, it was zero, so it incremented zero_count. This continued for all numbers. At the end, it printed the counts: 3 positive, 3 negative, 2 zero, and the filtered list contained only the positive numbers [5, 12, 7]. This shows how loops and conditionals work together to process and categorize data!

Example 4: Finding Maximum Value

Let's create a program that finds the maximum value in a list. This combines loops, conditionals, and variables.

Finding Maximum Value
numbers = [23, 45, 12, 67, 34, 89, 56]
max_value = numbers[0]  # Start with first number

for num in numbers:
    if num > max_value:
        max_value = num

print(f"The maximum value is: {max_value}")

How This Works

This program starts by assuming the first number is the maximum. Then it loops through each number in the list. For each number, it checks if it's greater than the current maximum. If it is, it updates max_value to that number. By the end of the loop, max_value contains the largest number. This is a common pattern for finding maximum or minimum values!

End-of-Lesson Exercises

Exercise 1: Build a Simple Calculator

Create two variables: num1 = 15 and num2 = 3. Create a variable operation = "*". Use if-elif-else to perform the operation and print the result.

Check if operation is "+", "-", "*", or "/" and perform the appropriate calculation.

Write your code above and click "Check Answer" to verify it's correct.

Exercise 2: Find Even Numbers

Create a list: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Use a for loop and an if statement to print only the even numbers.

Use for num in numbers:, then check if num % 2 == 0 to find even numbers.

Write your code above and click "Check Answer" to verify it's correct.