Course contentsShow
← Python
Lesson 88 of 1,0602. Control Flow and LogicFree lesson

Combining Loops with Conditional Logic

Learners will be able to filter or selectively process items within an iterable by nesting conditional statements inside a loop.

In this lesson, you will learn how to selectively process items in a list by nesting conditional statements inside your loops.

The Power of Filtering

So far, you’ve learned how to loop through a sequence of items and how to use if statements to control flow. When you combine them, you gain the power to "filter" data—performing actions only on the specific items that meet your criteria.

Think of this like a security guard at a door. The loop acts as the guard checking every single person in a line, while the conditional logic acts as the requirement for entry. If the person meets the criteria, they get in; if not, the guard ignores them and moves to the next person.

Seeing it in Code

Imagine you have a list of test scores and you want to identify only the scores that are passing (60 or higher). Instead of creating a new list manually, you can use a loop and an if statement to check each number:

scores = [45, 82, 59, 91, 30]

for score in scores:
    if score >= 60:
        print(f"Passed: {score}")
    else:
        print("Failed - keep studying!")

In this example, the loop iterates five times. During each iteration, the if statement evaluates the truthiness of score >= 60. If it is True, the program executes the block inside the if statement. If it is False, it jumps to the else block (or simply moves to the next loop iteration if no else were present).

Why Nesting Matters

By placing the if statement inside the loop, you ensure that your logic is applied to every single element individually. This allows your code to make intelligent decisions based on the data it encounters, rather than treating every item in your collection the same way. Whether you are cleaning up data, searching for specific values, or categorizing items, this pattern is a fundamental tool for managing flow control in Python.

Key Takeaway: Nesting conditional logic inside a loop allows you to inspect and process each item in a collection selectively based on whether it satisfies a specific condition.