Python programming nested for loops

Why do I Need Nested Loops in Python?

Nested loops are a very important concept in Python programming and Computer Science, are used in many algorithms. For example sorting algorithms such as Bubble Sort and Selection Sort rely on them, as does iterating through a 2D list. Sometimes while loops are used or a combination of while and for loops. In this article we focus specifically on nested for loops.

Python Nested For Loops Example 1

Type the following code into your favourite Python editor:

What will the output be? Take a moment to think about it and write down your answer before running the code and checking.

Did you get it right? See the video for an explanation.

Python Nested For Loops Example 2

Next we introduce an important concept: using the outer loop counter to control the range of the inner loop. See the example below.

What will the output be?

Why is this the output? Well:

  • for the first iteration, i = 0 so for the inner loop we have for j in range(0) which doesn’t get executed.
  • Next i = 1 and we have for j in range(1), giving only 1 0.
  • Finally i = 2 and we have for j in range(2), giving 2 0 and 2 1 stopping before j = 2 because range does that – as you should be getting used to by now.

Python Nested For Loops Example 3

Take a look at this pattern:

Can you use you new found skill with nested for loops to get Python to produce it for you?

A couple of tips:

  • To get Python not to add a new line after every print statement, add end="" as in print(i, end="").
  • To force the output onto a new line just use print() with no argument.

Have a good go at this before looking at the solution below.

So there it is – you should now be more comfortable and confident with nested for loops in Python. Learning to control iteration like this is going to make you a stronger programmer and help you succeed in you GCSE or A Level Computer Science exam.

Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}