Blog Post #44: Putting It All Together: if and for in the Same Program

Over the course of Part 2, we have mastered two major types of control flow: conditional logic with if/elif/else to make decisions, and repetition with for and while loops to perform actions multiple times. The real power of programming comes when we start combining these ideas.

In this post, we will explore one of the most common and useful patterns in all of programming: using an if statement inside a for loop. This allows us to iterate through a collection of items and make a decision about each one individually.

The Pattern: Iterate, Then Decide

The pattern is simple but incredibly powerful: “For every item in this collection, check if it meets a certain condition, and if it does, do something special.”

You see this pattern in real life all the time:

  • Going through a list of emails and flagging the ones that are spam.
  • Looking at a list of student grades and counting how many are passing.
  • Examining a list of products online and displaying only the ones that are on sale.

The code structure directly mirrors this logic. The if statement is simply indented inside the for loop’s body.

for item in some_list:
    # This code runs for EVERY item
    
    if condition_about_the_item:
        # This code runs ONLY for items that meet the condition

Example 1: Filtering a List

A common use of this pattern is to filter a collection, pulling out only the items that match our criteria. Let’s write a program that goes through a list of numbers and prints only the even ones.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("Even numbers in the list:")
for number in numbers:
    # We use the modulus operator from Post #13 to check for evenness
    if number % 2 == 0:
        # This print statement only runs if the 'if' condition is True
        print(number)

The for loop presents each number from the list to the if statement one by one. The if statement acts as a gatekeeper. Only if the condition (number % 2 == 0) is True is the print() statement inside the if block allowed to run.

Example 2: Sorting Items into Categories

Another powerful use of this pattern is to sort items from one collection into multiple new collections. Let’s write a program that sorts a list of student test scores into “passing” and “failing” lists. We’ll define a passing score as 60 or greater.

To do this, we’ll start with two empty lists. We’ll use the .append() method, which simply adds an item to the end of a list.

scores = [88, 92, 54, 78, 45, 99, 60]
passing_scores = []
failing_scores = []

for score in scores:
    if score >= 60:
        passing_scores.append(score)
    else:
        failing_scores.append(score)

print(f"Passing scores: {passing_scores}")
print(f"Failing scores: {failing_scores}")

The output will be:

Passing scores: [88, 92, 78, 99, 60]
Failing scores: [54, 45]

For each score in the original list, our if-else block makes a decision. If the score is passing, it gets appended to the passing_scores list; otherwise, it’s appended to the failing_scores list. By the time the loop is finished, every score has been sorted into the correct category.

What’s Next?

Combining iteration with decision-making is a fundamental skill in programming. The for...if pattern allows you to process large amounts of data, applying specific logic to each individual item. You will find yourself using this pattern constantly.

This post concludes the new concepts for Part 2. We’ve covered everything from boolean logic to loops and how to combine them. It’s time to put all this knowledge to the test in a final, fun project. In Post #45, we will recap Part 2 and build a complete number guessing game from scratch.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment