Control Flow: The for Loops

Nested for Loops

When for loops are used inside one another, the inner loops are called nested for loops. The indentation rules apply to any inner levels of nested code. An example below displays a rectangular pattern on the console output with given width and height:

def draw_rectangle(width_of_rectangle, height_of_rectangle):

    for h in range(height_of_rectangle):
        for w in range(width_of_rectangle):
            print("#", end='')
        print()


width = 3
height = 5

draw_rectangle(width, height)

Output:

###
###
###
###
###

Please be careful when choosing the names of the loop variables in nested loops. If you choose the same variable name as the outer loop, you might observe weird results, unless that is your actual intention.

The following example prints a sector of the Sudoku tiles as

1  2  3  
4  5  6  
7  8  9 
for h in range(3):
    for w in range(3):
        print((3*h + w + 1), " ", end='')
    print()

Try the same example by replacing both h and w with _.

Recall that the print() function by default adds a newline character at the end of its argument and to prevent that newline you can use the "end=''" syntax we discussed earlier.

Attention: The loop variables are different for each of the loops.

What is the alternative solution for this problem using a single for loop?

Python can replicate a string literal as much as required by using the * operator. The following code will output the same rectangle, however, you will need nested loops for many other problems other than this simple example:

def draw_rectangle(width_of_rectangle, height_of_rectangle):

    for h in range(height_of_rectangle):
        print("#" * width_of_rectangle)


width = 3
height = 5

draw_rectangle(width, height)