Python Tutorial for Beginners

Python For Loop

What is For Loop in Python?

Iterating through a sequence is done with a For loop. This is more like an iterator method seen in other object-oriented programming languages than the For keyword in other programming languages.

The For loop allows us to run a sequence of statements once for each item in a list, tuple, set, or other data structure.

Python for loop Syntax

for ( init; condition; increment ) :

    #  statement(s)

Code:

# Print each fruit in a fruit list:

fruits = ["pear", "melon", "orange"]

for x in fruits:

 print(x)

Output:

pear
melon
orange

range() functions

In Python, the range() function returns the sequence of numbers inside a given range.

The range() method returns a number series that starts at 0 and advances by 1 (by default) until it reaches a given value.

Example:

Make a sequence of numbers from 0 to 6, and print each item in the sequence:

for n in range(7):

  print(n)

Output:

0
1
2
3
4
5
6

The range() method has a default beginning value of 0. But you may change it by passing it a parameter: range(1, 5), which indicates numbers from 1 to 5 (but not including 5).

Example 1:

for n in range(1,5):

  print(n)

Output:

1
2
3
4

The range() method increases the sequence by one, by default. However a third parameter can be used to set the increment value: range(1, 10,2) is a function that takes numbers from 1 to 10 (but not including 10) and adds 2 to the sequence.

Example 2:

for n in range(1,10,2) :

  print(n)

Output:

1
3
5
7
9

The range() method increments the sequence by 1, by default. However, a third parameter can be used to set the increment value: range(10,5,-1):  range(10,5,-1), which means values from 10 to 5 (but not including 5) and decrement the sequence by -1.

Example:

for n in range(10,5,-1) :

  print(n)

Output:

10
9
8
7
6

For loop with else

In a For loop, the else keyword indicates a block of code that will be performed after the loop is finished:

Example:

Print all numbers from 0 to 6, and print a message when the loop has ended:

for y in range(7):

  print(y)

else:

  print("finished! ")

Output:

0
1
2
3
4
5
6
finished!

Nested loop

The For loop is used in Python to iterate over a series of objects such as a list, string, tuple, and other iterable objects like range.

Example:

# outer loop

for x in range(1, 10):

    # nested loop

    # to iterate from 1 to 9

    for y in range(1, 10):

        # print multiplication

        print(x * y, end=' ')

    print()

Result:

1 2 3 4 5 6 7 8 9 
2 4 6 8 10 12 14 16 18 
3 6 9 12 15 18 21 24 27 
4 8 12 16 20 24 28 32 36 
5 10 15 20 25 30 35 40 45 
6 12 18 24 30 36 42 48 54 
7 14 21 28 35 42 49 56 63 
8 16 24 32 40 48 56 64 72 
9 18 27 36 45 54 63 72 81

QUIZ!

What will be the outcome of the Python code below?

x = ['a', 'c']

for i in x:

    i.upper()

print(x)

Select the correct answer

Did you find this article helpful?