Loops

Control Statements and Nested Loops

Learn how to control the flow of a loop using the break and continue statements. We will also explore the concept of nesting loops for more complex iterations.


Let's consider the following tuple representing your hypothetical yearly income:

yearly_income = (250000, 130000, 320000, 320000, 220000, 300000)
Python

We want to find out when you'll become a millionaire.

To do so, we'll use a for-loop to iterate through the years and calculate your total income.

Here's the loop. It notifies us once the total income reaches one million or more:

yearly_income = (250000, 130000, 320000, 320000, 220000, 300000) total_income = 0 years = 0 for income in yearly_income: total_income += income years += 1 print(years) if total_income >= 1000000: print('Millionaire 💰💰💰')
Python
Output

Nice, in year 4 you'll already be a millionaire.

However, let's pause the excitement for a moment because there's an issue with our code.

The task of finding your lucky year was completed after the fourth iteration of the loop.

But it kept iterating through the entire sequence of years. That is pretty inefficient code.

We need to find a way to stop the loop once our task has been achieved.

That's where we can use the break statement.

Let's give it a try. Here, we include a break statement right after the print statement within the if-condition:

yearly_income = (250000, 130000, 320000, 320000, 220000, 300000) total_income = 0 years = 0 for income in yearly_income: total_income += income years += 1 print(years) if total_income >= 1000000: print('Millionaire 💰💰💰') # terminate loop here break
Python
Output

Great, now the loop terminates after the condition is fulfilled.

A break statement can be placed anywhere within the code block of a loop.


What will be the output?

for i in range(4): print(i) break
Python

What will be the output?

for i in range(4): break print(i)
Python

What will be the output?

for i in range(4): if False: break print(i)
Python

Another statement that you can use to control the flow of a loop is the continue statement.

continue will cause the loop to directly jump to the next iteration.

Let's consider the following loop.

for x in 'P#yt#h#on': print(x)
Python
Output

We print each character in the string. But, there are some unwanted # symbols in the string.

Using continue allows us to skip these unwanted symbols:

for x in 'P#yt#h#on': if x == '#': continue print(x)
Python
Output

Whenever Python encounters the continue statement, it skips the current iteration and moves on to the next one.

Thereby, we effectively bypass any code that would have otherwise followed in this iteration.


What will be the output?

for i in range(-2,3): if i < 0: continue print(i)
Python

What will be the output?

sum = 0 for i in range(1,7): # check if i is uneven if i % 2 != 0: continue sum += i print(sum)
Python

Sometimes, you are dealing with more complex data than just simple sequences.

Consider the following representation of a tic tac toe game:

tic_tac_toe = [ ['X', 'O', 'X'], ['O', 'X', 'O'], ['O', 'O', 'O'] ]
Python

Here, we have three lists within a list, with each inner list representing a row of the game.

To access every element within these lists, we need to write nested loops:

tic_tac_toe = [ ['X', 'O', 'X'], ['O', 'X', 'O'], ['O', 'O', 'O'] ] for row in tic_tac_toe: for item in row: print(item)
Python
Output

What's going on here?

First, we iterate over each row of the game. And within each iteration, we create another loop in order to iterate over every element within the current row.

This example might make it a bit more clear:

for x in range(2): for y in range(3): print('Outer: ', x, 'Inner: ', y)
Python
Output

Before the outer loop completes its iteration, it generates an inner loop that iterates over its own entire sequence.

What about break and continue statements in nested loops?

You can use the break and continue statements both in inner and outer loops.

But they will only affect the loop they're used in.

For example, here the break statement only terminates the inner loop:

for x in range(3): for y in range(5): if x + y > 2: print('Break inner') break print('Outer: ', x, 'Inner: ', y)
Python
Output

Once the inner loop is terminated by the break statement, the outer loop continues and creates a new inner loop in the next iteration.


What will be the output?

for x in range(3): sum = 0 for y in range(3): sum += y print(sum)
Python