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

Integrating Conditional Logic Inside Iterative Structures

Apply filtering criteria to individual elements during iteration by placing conditional statements directly within the body of a loop.

Integrating Conditional Logic Inside Iterative Structures

In this lesson, you will learn how to make your loops "smarter" by applying specific criteria to each element as you process a collection.

The Power of Choice

Up until now, you have learned how to iterate over every single item in a list or range. However, real-world data is often messy, and you rarely want to treat every item exactly the same way. By placing an if statement inside the body of a for loop, you create a "gatekeeper" that decides whether to perform an action on a specific element.

Think of a loop as a conveyor belt moving items past you. Without conditional logic, you have to interact with every item. By adding an if statement, you can reach out and grab only the items that meet your requirements, letting the others pass by untouched.

Practical Example

Imagine you have a list of test scores, and you want to print a congratulatory message only for those who passed with a score of 70 or higher:

scores = [55, 82, 41, 95, 68, 77]

for score in scores:
    if score >= 70:
        print(f"Great job! You scored {score}.")

In this code, the loop visits every number in scores. However, the print function is protected by the if statement. If the condition score >= 70 is False, the loop simply moves to the next item without executing the code inside the if block.

Why This Matters

This pattern is the foundation of data filtering. Whether you are searching for specific names in a database, finding odd numbers in a sequence, or cleaning up user input, this structure allows your code to act dynamically based on the characteristics of the data itself. You are no longer just looping; you are analyzing and selecting.

Key Takeaway: Placing an if statement inside your loop body allows you to selectively process only the items that satisfy your specific criteria.