Python For Loops



Explanation

A more in depth look into Python For loops, additional uses and examples.

In python, for loops iterate over a sequence (List, Dictionaries, range, set, strings and arrays), with the most common being the range sequence, which allows the loop to repeat a certain number of times. Infact, the range function is used so often with for loops, some people end up believing that its a part of the for loop syntax. There are in-fact, many more uses.

Syntax

Structure for making a for loop.

for x in (iteratable object):
      #Statement to be executed

range function

To repeat a block of code for a set number of times, we use the range function.

This function creates a sequence of numbers that a for loop can iterate through. The range function takes three parameters. The first is the starting number, (default is zero) the second is the ending number and the third is the increment number (default is one).

Keep in mind that the range function has an exclusive nature, which means that the last number in the sequence is not included. If the range function parameters are 0-5, then the number “5” will not be included. Example shown below.

for x in range(5):
    print(x)
0
1
2
3
4

Decrementing the range function

By changing the third parameter to a negative number, we can decrement the loop. Remember to switch the starting and end points accordingly.

Remember to mention all three parameters when adding this third parameter, else python will get confused! If you write, range(5, -1), it will think -1 is the second parameter, instead of the third.

for x in range(5, 0, -1):
    print(x)
5
4
3
2
1

Iterating over sequences

Here are some examples of using for loops to iterate over others sequences like Lists and dictionaries.

Lists

a = ["Apples","Oranges","Grapes","Mango"]

for x in a:
    print(x)
Apples
Oranges
Grapes
Mango

Dictionaries

a = {"Shop1":200, "Shop2":230,"Shop3":190, "Shop4":270}

for x in a:
    print(x)
Shop1
Shop2
Shop3
Shop4

As you can see from the output, only the “key” part of the dictionary is being displayed. Check the Python Dictionary page to understand how to get the “value”.

Strings

Python treats each individual character in a string as a separate entity, allowing to iterate over each of them separately.

a = "abcde"

for x in a:
    print(x)
a
b
c
d
e

Control Statements – For Loops

break

The break statement is used to terminate a loop before it’s completion.

Below is the code for a program that that reads through a list of numbers and stops when it encounters -1.

nums = [1,3,6,4,2,-1,9]

for x in nums:
    if x == -1:
        break
    print(x)
1
3
6
4
2

continue

The continue statement will stop the current iteration of a loop and skip to the next, avoiding any statements in between.

for x in range(1,6):
     if x==2:
        continue
     print(x)
1
3
4
5

Pass

Python’s structure makes it compulsory for code blocks (if else, def, for) to not be empty. Leaving a code block empty will result in an error.

The pass isn’t very commonly used as it doesn’t have many uses, but it’s still something interesting to know. If you want to make a code block, but leave it blank for a while, you can simply put a pass statement in it.

for x in range(5):
    pass

Extra Examples:

A demonstration of nested for loops. A nested loop refers to a loop within a loop.

for x in range(1,5):
    for y in range(1,3):
        print(x,y)

Use of the else statement in for loops. The else statement is executed once the loop is over.

for x in range(1,5):
    print(x)
else:
    print("End of Loop")
1
2
3
4
End of Loop

This marks the end of the Python For Loops Article. Any suggestions or contributions for Coders Legacy are more than welcome. Any questions can be directed into the comments section below.

Leave a Reply

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