Introduction to Computer Science/3.9 Nesting Your Logic

3.9 Nesting Your Logic



🎯 Learning Goals for This Page
  • Define "nested control structure."
  • Write a program that uses an if statement inside a for loop.
  • Understand how indentation is used to show multiple levels of nesting.

Combining Your Tools

The tools we've learned this week—selection (if) and repetition (for/while)—are powerful on their own. But their real power is unlocked when you combine them. This is called nesting.

You can put any control structure inside another. The most common pattern you will use is placing an if statement inside a loop to make a decision about every single item in a sequence.

Indentation is Everything (Again!)

Python uses indentation to understand which code belongs to which block. When you nest structures, you just use another level of indentation.

for i in range(5):
    # This line is indented once, so it's inside the FOR loop.
    print(f"Checking the number {i}...")

    if i % 2 == 0:
        # This line is indented TWICE.
        # It's inside the IF statement, which is inside the FOR loop.
        print("   ...it is an even number.")


Live Example: The Even/Odd Checker

This program uses a for loop to iterate through numbers from 1 to 10. Inside the loop, it uses an if/else statement to check if each number is even or odd. The key to its logic is a special tool we learned in Unit 1.

💡 Tool Spotlight: The Modulo Operator (%)

Remember the modulo operator from our calculator lesson? It gives you the remainder of a division. This is incredibly useful for solving logical problems. By definition, an even number is any number that can be divided by 2 with a remainder of 0. That's the secret to this program's logic: the condition if current_number % 2 == 0: is just a programmer's way of asking, "Is this number even?"

Run the code below to see how it works. Then, try the challenges printed at the end!

Python 3Initializing...
Loading code editor...
Program output will appear here...
The Gateway to Complex Logic

Nesting is the key to solving almost any complex programming problem. The "Guess the Number" game will require a loop with an if/elif/else block nested inside it. Understanding this structure is essential for success.

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...