Welcome to the sixth and final lesson of our first module on Python fundamentals. In the last two lessons, you learned about conditional statements (if/elif/else) to make decisions and loops (for/while) to perform repetitive tasks. These are the foundational pillars of programming.
Today, we will bring these concepts together. You will learn how to combine conditionals and loops to write programs that can iterate through data and make intelligent decisions about each piece of information they encounter. Mastering this combination is the key to moving from writing simple scripts to designing complex algorithms, which are at the heart of every AI and machine learning model.
By the end of this lesson, you will be able to combine conditional statements and loops to solve simple, but important, logic problems.
The Core Pattern: Making Decisions Inside Loops
The most common and powerful pattern you'll use is placing an if statement inside a loop. This allows your program to perform a check on every single item in a sequence and act accordingly.
Think of it like sorting mail. The loop is the act of going through each letter in the pile (for letter in mail_pile). The conditional is how you decide what to do with each one (if letter is a bill, put it in the 'to pay' stack; else, put it in the 'personal' stack).
Let's start with a practical exercise that demonstrates this. In the previous lesson, you were introduced to an exercise about finding even numbers. Let's revisit it, focusing on how the for loop and the if statement work in concert.
Hands-On Practice 1: Finding and Counting Even Numbers
Your task is to write a program that iterates through the numbers from 1 to 9, identifies which ones are even, prints them, and finally prints a count of how many even numbers were found.
Open a new Jupyter Notebook and try to write this code. Remember, you'll need:
- A
forloop withrange()to go through the numbers. - An
ifstatement to check if a number is even (the modulo operator%is key here). - A counter variable that you initialize before the loop and increment inside the
ifblock.
If you need guidance, the following video segment provides a complete walkthrough of this exact problem.
Python For Loops - Python Tutorial for Absolute Beginners
This video from Programming with Mosh clearly demonstrates how to combine a for loop with an if statement to solve this logic problem.
Watch the exercise walkthrough from the beginning to the end. Pay close attention to how the counter variable is updated only when the if condition is met.
A Classic Logic Puzzle: FizzBuzz
Now that you're comfortable with the basic pattern, let's tackle a classic programming puzzle called "FizzBuzz." It's a favorite in coding interviews because it elegantly tests your understanding of loops and conditionals.
The task is as follows:
Write a program that prints numbers from 1 to 100. However:
- For multiples of three, print "Fizz" instead of the number.
- For multiples of five, print "Buzz" instead of the number.
- For numbers which are multiples of both three and five, print "FizzBuzz".
The key to solving this is the order of your if/elif/else checks. You must check for the most specific condition first (multiples of both 3 and 5).
The following article provides a clear explanation and solution.
Python For Loops and If Statements Combined (Data ...
This article from Data36 breaks down the FizzBuzz problem and shows a clean solution using a for loop containing an if/elif/else block.
First, read the section describing the task. Then, carefully study the code solution. Notice the use of the and operator and why the if i % 3 == 0 and i % 5 == 0: check must come first.
Conditional Repetition with while Loops
The same principle applies to while loops. You can use a while loop to repeat an action until a condition is met, while using if statements inside to control the flow or check for a reason to exit.
A very common use case is validating user input. Imagine a program that needs a user to enter their age. You can't accept a negative number. A while loop can continuously re-prompt the user until they provide valid input.
The following video from Bro Code demonstrates this perfectly.
While loops in Python are easy! ♾️
This segment shows a practical example of forcing a user to enter a number within a specific range using a while loop and conditional logic.
Watch the example starting from this section. Observe how the while loop's condition (num < 1 or num > 10) keeps the loop running as long as the input is invalid.
Hands-On Practice 2: A Simple Guessing Game
Let's apply this concept. Write a simple guessing game:
- Create a variable
secret_wordand assign it a string value (e.g., "python"). - Use a
while True:loop to create an infinite loop. - Inside the loop, ask the user to guess the word using the
input()function. - Use an
ifstatement to check if their guess matches thesecret_word. - If they guess correctly, print "You got it!" and use the
breakstatement to exit the loop. - If they guess incorrectly, print "Wrong, try again."
This exercise combines a while loop, an if/else conditional, and the break statement to control the loop's execution based on user input.
Putting It All Together: An Inventory Check
Your background in administration and inventory management provides an excellent real-world context for applying these skills. Let's design a simple script to monitor product stock levels.
Imagine you have your inventory data represented as a list of lists, where each inner list contains a product name and its current stock quantity.
# Product, Quantity
inventory = [
["stapler", 20],
["pen", 5],
["paper_ream", 0],
["tape", 35],
["highlighter", 3]
]
Your task: Write a program that iterates through the inventory list and prints a status report.
- Create a
forloop to iterate through eachproductin theinventorylist. - Inside the loop, use an
if/elif/elseblock to check the stock quantity (product[1]).- If the quantity is
0, print"[Product Name] - OUT OF STOCK". - If the quantity is greater than
0but less than or equal to5, print"[Product Name] - Low stock, re-order soon.". - Otherwise (if the stock is more than 5), print
"[Product Name] - Stock is sufficient.".
- If the quantity is
This problem requires you to loop through a data structure and apply a set of rules to each item—a task fundamental to data processing and analysis.
Solution Code:
Try to write the code yourself first. Once you're ready, you can compare your solution with the one below.
inventory = [
["stapler", 20],
["pen", 5],
["paper_ream", 0],
["tape", 35],
["highlighter", 3]
]
for product in inventory:
product_name = product[0]
stock_level = product[1]
if stock_level == 0:
print(f"{product_name} - OUT OF STOCK")
elif stock_level > 0 and stock_level <= 5:
print(f"{product_name} - Low stock, re-order soon.")
else:
print(f"{product_name} - Stock is sufficient.")
Conclusion
In this lesson, you've bridged the gap between knowing individual programming concepts and combining them to create functional logic. This is a significant milestone in your journey towards building complex applications.
Here are the key patterns we covered:
- Filtering and Categorizing: Using an
ifstatement inside aforloop allows you to examine each item in a sequence and handle it differently based on its properties. - Conditional Repetition: Using an
ifstatement inside awhileloop allows you to repeat a process until a specific condition is met, often usingbreakto exit once the goal is achieved. - Algorithmic Thinking: The process of breaking down problems like FizzBuzz or the inventory check into loops and conditional steps is the essence of writing algorithms.
You have now completed the first module and have a solid grasp of Python's fundamental building blocks. In our next lesson, we will begin a new module by exploring functions. Functions will allow us to package the logic we've learned to write into clean, reusable blocks, making our code more organized, efficient, and powerful—a crucial step towards building sophisticated AI models.