Nested loop in Python

A nested loop is a loop that is programmed inside another loop. We can nest any type of loop inside any type of loop. That is, we can put a while loop in a for loop, a for loop inside a while loop, a while loop inside a while loop, or a for loop inside a for loop.

Let us take an example: in this example, we want to create a program that will give us a list of even numbers between 1 and 10. We will nest a while loop inside a for loop:

even_list = []
for item in range (1, 11):

    while item % 2 == 0:
        even_list.append(item)
        break
print ("Even Numbers: ", even_list)

Do you see the break statement in that code? The break statement is used to stop the loop before the program loops through all the items. It will stop or pause it to run the next line.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials