Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python For Loop Statement


Python Looping Statements

In python, for and while are looping statements.

Looping statements help to execute the specific blocks of code repeatedly.

For loop statement

Python for statement iterates over the items of any sequence (a list, tuple, set, dictionary, string) in the order by which they appear.

Created with Raphaƫl 2.3.0Start for loop iterationCondition (check item remain)Execute for block statementsand try next itemEnd for loop iterationYesNo

For loop flowchart

Example
numbers_list = [
    0, 1, 2, 3, 4, 5
]
for number in numbers_list:
    print(number)
0
1
2
3
4
5

In the above example, we declared a list of elements from 0 to 5 and assigned that list to the numbers_list variable. Using the for loop statement, we iterate that list and print the numbers.


Python break keyword

The break keyword helps to stop the iteration of looping statements.

Example
numbers_list = [
    0, 1, 2, 3, 4, 5
]
for number in numbers_list:
    if number == 3:
        break
    print(number)
0
1
2

In the above example, we used a for loop to print the numbers 0 to 5. However, if the number equals 3 (number == 3), then after we break the for loop iteration since the number only prints from 0 to 2, and then it stops.


Python continue keyword

The continue keyword allows us to stop the current iteration of the loop and continue with the next.

Example
numbers_list = [
    0, 1, 2, 3, 4, 5
]
for number in numbers_list:
    if number == 3:
        continue
    print(number)
0
1
2
4
5

In the above example, we used a for loop to print the numbers 0 to 5. However, if the number equals 3 (number == 3), call the continue keyword because calling the continue will skip the current iteration and move to the next. In the output, you see the numbers 0 to 5 are displayed, but the number 3 is missing.


Python else clause in for loop statement

After for loop iteration is complete, then else block statements will execute.

Example
numbers_list = [
    0, 1, 2, 3, 4, 5
]
for number in numbers_list:
    print(number)
else:
    print("For loop iteration complete.")
0
1
2
3
4
5
For loop iteration complete.

In the above example, we used a for loop to print the numbers 0 to 5. After the for loop iteration completes, it executes an else block and prints the statement "For loop iteration complete.".


Python else clause in for loop with the break keyword

Using the break keyword for loop iteration stops, and in this case, the else block will not execute.

Example
numbers_list = [
    0, 1, 2, 3, 4, 5
]
for number in numbers_list:
    if number == 3:
        break
    print(number)
else:
    print("For loop iteration complete.")
0
1
2

As you can see, we added a condition if the number equals 3 (number == 3), then break the for loop iteration. In this case, the numbers only print from 0 to 2.