Python For Loops


Python For Loops

A for loop is used for iterating over a sequence (list, tuple, set, dictionary, string).

In Python, the for keyword is a little different from other programming languages. It works more like an iterative method.


Syntax of For Loop

The syntax of the for loop statement can be given as follows:

for var in sequence:
    statement(s)

Here above, the var is the variable that takes the item's value inside the sequence (collection) on every iteration.

The statement(s) in the loop body is separated by an indentation, and it is executed once for each item in the sequence.

The loop continues until it reaches the last item of the sequence.


Flowchart of For Loop

The flowchart of the for loop statement is as follows:

Flowchart of For Loop in Python

Python for Loop - Example

Let us see the following example.

vegetables = ["artichoke", "broccoli", "potato", "tomato"]

for x in vegetables:
    print(x)

After executing the above code, the output will be as follows:

artichoke
broccoli
potato
tomato

Looping Through a String

In Python, strings are considered as iterable objects. They contain a sequence of characters.

Let us see the following example:

for x in "Hello World!":
    print(x)

When you run the above code, the output will be:

H
e
l
l
o
 
W
o
r
l
d
!

The break Statement

In Python, you can use the break statement to stop the loop before it is finished.

Let us see the following example: we will exit the loop when the value of x is "potato".

vegetables = ["artichoke", "broccoli", "potato", "tomato"]

for x in vegetables:
    print(x)
    if x == "potato":
        break

After executing the above code, the output will be:

artichoke
broccoli
potato

In the following example, we will exit the loop when the value of x is "potato", but this time the break comes before the print, so the item "potato" will not be displayed.

vegetables = ["artichoke", "broccoli", "potato", "tomato"]

for x in vegetables:
    if x == "potato":
        break
    print(x)

The output:

artichoke
broccoli

The Continue Statement

You can use the continue statement to stop the loop's current iteration and continue with the next.

In the following example, we will print all the vegetables list items except the "potato" item.

vegetables = ["artichoke", "broccoli", "potato", "tomato"]

for x in vegetables:
    if x == "potato":
        continue
    print(x)

After executing the above code, the output will be:

artichoke
broccoli
tomato

The range() Function

The range() function is used to generate a sequence of numbers. It starts from 0 by default and increments by 1 (by default), and finishes at a specified number.

For the range() function you can define the start, stop and size as range(start, stop, setp_size).

The range() function is lazy. It doesn't generate all the numbers at one time, but it generates the next number on every cycle of the loop.

If you want the range() function to output all its items, you can use the list() function.

Let us see the following example to clarify more.

print(range(5))

print(list(range(5)))

print(list(range(3, 12)))

print(list(range(5, 50, 5)))

The output of the above code:

range(0, 5)
[0, 1, 2, 3, 4]
[3, 4, 5, 6, 7, 8, 9, 10, 11]
[5, 10, 15, 20, 25, 30, 35, 40, 45]

You can use the range() function in for loops to iterate through a sequence of numbers.

for x in range(7):
    print(x)

Output:

0
1
2
3
4
5
6

Note: Note that range(7) does not output the values from 0 to 7, but the values from 0 to 6.

You can also combine the range() function with the len() function to iterate through a sequence using indexing.

fruits = ["kiwi", "grape", "mango", "raspberry"]

for i in range(len(fruits)):
    print(fruits [i])

The output of the above code will be:

kiwi
grape
mango
raspberry

For Loop with Else

A for loop can have an optional else block. The else part is executed when the loop is finished.

In the following example, we will print all numbers from 0 to 5 and print a message when the loop is finished.

for x in range(5):
    print(x)
else:
    print("The end of the loop")

After executing the above code, the output will be:

0
1
2
3
4
The end of the loop

The else part is ignored when the break statement is used to stop a for loop. However, a for loop's else part executed if not break happens.

In the following example, we will use the break statement to stop a for loop, so the else part will be ignored.

for x in range(5):
    if x == 3:
        break
    print(x)
else:
    print("The end of the loop")

The output will be as follows:

0
1
2

Note: If the break statement is used to stop a for loop, the else block will NOT be executed.


Nested Loops

The nested loop is a loop inside a loop.

The "inner loop" is executed until the finish every time for each iteration of the "outer loop".

In the following example, we will print the same fruit with three different numbers.

fruits = ["kiwi", "grape", "raspberry"]

for x in fruits:
    for y in range(3):
        print(x, y)

The output of the above code will be as follows:

kiwi 0
kiwi 1
kiwi 2
grape 0
grape 1
grape 2
raspberry 0
raspberry 1
raspberry 2

The pass Statement

In Python, the for loops cannot be empty. In the case that you want to have a for loop with no content inside it, you can use the pass statement to avoid getting an error.

for x in range(5):
    pass

The above code will not generate an output.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.