Recommended Books

Python Loops



There are two types of Loops in python, the while loops and the for loops. Click on the links to check individual articles on each loop, which deal with each loop in more detail.

StatementDescription
whileRepeats a block a code while a given condition holds true.
forRepeats a block of code for a given number of times. Can also be used to iterate through collection types variables, like Lists and Arrays.

You can further increase the functionality of loops by creating “Nested loops”. Nested loop refers to a loop that exists within another loop.


Python Loop control:

Loop control statement help us manipulate Python loops during their execution.

NameDescription
breakWhen a loop encounters this statement during its execution, it will immediately stop and “break”, moving to the next statement after the loop.
continueThe loop will stop it’s current iteration, and move on to the next iteration.
passpass statement is required to be used in empty loops, due to the requirement that loops must have some code within them. Basically, you use it when you don’t want any code to be executing.

Python Loops Examples:

Be vary of capitalization while writing loops, everything must be in lowercase.

While Loops:

While the condition x < 5 holds true, the loop will continue running. Once the condition x < 5 becomes false, the loop terminates.

x = 0
while x < 5:
    print(x)
    x = x + 1
0
1
2
3
4

For Loops:

This for loops iterates over the list “shopping” outputting each element separately.

shopping = ["Apples","Oranges","Grapes"]
for x in shopping:
    print(x)
Apples
Oranges
Grapes

Nested Loops:

A Nested loop is a loop within another loop. Using Nested loops in our code can prove very useful and help us iterate through sequences in new ways. The most common use of Nested loops comes in iterating through other Nested or multi-dimensional items like 2-D arrays and Nested Lists.

What’s happening here is that there is a List, which further contains two lists within it. So its a “nested list”. If we iterate through it normally, we’ll just get 2 lists, which you can even see in the example output. Iterating through the list twice gives us each element separately.

shopping = [["Apples","Oranges","Grapes"],["Pots","Spoons","Forks"]]
for x in shopping:
    print(x)
    for i in x:
        print(i)
['Apples', 'Oranges', 'Grapes']
Apples
Oranges
Grapes
['Pots', 'Spoons', 'Forks']
Pots
Spoons
Forks

While there is no limit to the amount loops you can nest into each other, for readability’s sake avoid going above 3.


This marks the end of the Python Loops article. Any suggestions or contributions for CodersLegacy are more than welcome. Relevant questions can be asked in the comments section below.

Leave a Reply

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