So far, we've explored how to make decisions using if, elif, and else statements, and how to repeat actions with for and while loops. Now, let's combine these powerful tools to create more complex and dynamic programs. This is where nested control flow comes into play – essentially, putting control flow statements inside other control flow statements.
Imagine you need to check if a student passed a course, and if they did, then check if they achieved a certain grade to qualify for honors. This involves a decision within another decision. Or, consider iterating through a list of students and, for each student, iterating through their list of assignments to check if they're all completed. This is a loop within a loop.
Nesting allows us to build sophisticated logic. The key is that the inner control flow statement executes entirely for each iteration or condition of the outer one. Let's start with nesting if statements.
grade = 85
aplicable_for_honors = False
if grade >= 70:
print("Student passed the course.")
if grade >= 90:
print("Student achieved honors!")
aplicable_for_honors = True
else:
print("Student did not pass the course.")
if aplicable_for_honors:
print("Proceed with honors application.")In this example, the inner if grade >= 90: statement is only checked if the outer condition grade >= 70 is true. This is a clear demonstration of how decisions can be layered.
We can also nest loops. A common scenario is iterating over a 2D structure, like a grid or a matrix. Think of a multiplication table, where for each row, you iterate through each column to calculate the product.
for row in range(1, 6):
for col in range(1, 6):
product = row * col
print(f"{row} * {col} = {product}")
print("---") # Separator for each rowHere, the inner for col in range(1, 6): loop completes all its iterations for each single iteration of the outer for row in range(1, 6): loop. This creates a structured way to process data in multiple dimensions.