Python For Loop Tutorial with Examples

In Python, the 'for' loop provides a mechanism for traversing iterable entities, including tuples, lists, dictionaries, and strings, continuing until it either exhausts the sequence or meets a specified condition. Upon the completion of each iteration, the 'for' loop advances to the succeeding step.

Syntax of the Python for Loop

It has the following syntax:

Example

# syntax of for loop

for var_name in sequence:

    # lines of code

    # to be executed

Parameter(s):

  • var_name: A name of a variable assigned to each element in the given sequence.
  • sequence: Sequence refers to iterable elements such as lists, tuples, dictionaries and strings.
  • Simple Python for Loop Example

Let's examine a straightforward example to gain insight into the functioning of the For Loop in Python.

Example

Example

# printing numbers using for loop

for i in range(1,7): #Here we have used for loop

    print (i)

Output:

Output

1

2

3

4

5

6

Explanation:

In the preceding illustration, we utilized a for loop in conjunction with the range function to display numbers from 1 to 6.

Flowchart of the for Loop in Python

The subsequent flowchart illustrates the operation of a 'for' loop:

Step 1: The 'for' loop traverses through every element within the sequence.

Step 2: The process will verify if the final element in the sequence has been attained; if it has not, the loop will revert to the previous statement.

Step 3: When the last element in the series is encountered, the loop will terminate.

Examples of Python for Loop

Let us now examine a few fundamental illustrations of the Python for loop:

Printing Elements from a List or Tuple

In Python, Lists and Tuples serve as data structures designed to hold multiple elements within a single variable. By utilizing the 'for' loop, we can traverse each item in these ordered data structures.

Let us take a look at the following example:

Example

Example

# given list

cars = ["Tata", "Honda", "Mahindra", "Suzuki", "BMW"]

# using for loop to iterate each element from the list

for brands in cars:

  print(brands)	# printing elements

Output:

Output

Tata

Honda

Mahindra

Suzuki

BMW

Explanation:

In this illustration, we are presented with a list. We utilized a 'for' loop to traverse each element within the list and displayed them.

Python Program to Print Factorial of a Number

Let's examine an example that demonstrates how to calculate and display the factorial of a given number. In this Python program, we will utilize a 'for' loop to traverse from 1 up to the specified number, cumulatively multiplying these values to compute the factorial of that number.

Example

Example

# taking input from the user

num = int(input("Enter a Number: "))

# initializing the initial factorial

fact = 1

# base cases

if num < 0:

    # factorial not defined for number less than 0

    print("Not Defined!")

elif num == 0 and num == 1:

    # factorial = 1 for number equal to 0 and 1

    print(f"{num}! = {fact}")

else:

    # using the for loop to iterate from

    for i in range(2, num + 1):

        # multiplying the current value with the factorial

        fact = fact * i

    # printing the factorial of the number

    print(f"{num}! = {fact}")

Output:

Output

Enter a Number: 5

5! = 120

Explanation:

In this instance, we employed the 'for' loop to traverse through the range starting from 2 up to the specified number, multiplying the value obtained from each iteration with the previously initialized factorial value. Consequently, we were able to compute the factorial of the given number.

Nested for Loop

In Python, a nested 'for' loop denotes a 'for' loop that exists within the body of another 'for' loop. This construct is commonly employed when traversing multi-dimensional data structures, creating patterns, or executing tasks that necessitate several levels of iteration.

Syntax:

Nested for loop has the following syntax:

Example

for outer_var in outer_iterable:

    for inner_var in inner_iterable:

        # Code to be executed in the inner loop

    # Code to be executed in the outer loop (after the inner loop completes)

Now, let's examine a few instances to grasp how nested for loops function.

Printing the Elements of the Matrix

Let us examine an illustration of how to display the components of a 3x3 matrix utilizing a nested for loop.

Example

Example

# given matrix

matrix_3x3 = [

    [13, 4, 27],

    [22, 16, 8],

    [5, 11, 19]

    ]

print("Given Matrix:")

# using nested for loop to iterate through each element of the matrix

for row in matrix_3x3:

  for col in row:

    print(col, end = ' ')

  print()

Output:

Output

Given Matrix:

13 4 27

22 16 8

5 11 19

Explanation:

In the preceding illustration, a 3x3 matrix is presented. We employed a nested for loop to traverse through the rows and columns of the specified matrix and display the elements.

Pyramid Pattern using Nested for Loop

Next, we will examine the subsequent program designed to construct a Pyramid utilizing a Nested for Loop.

Example

Example

row = int(input("Enter number of rows: "))

for i in range(1, row + 1):

    # Print spaces

    for j in range(row - i): #nested loop used

        print("  ", end="")

    # Print stars

    for stars in range(2 * i - 1):

        print("* ", end="")

    print()

Output:

Output

Enter number of rows: 5

         *

      * * *

    * * * * *

  * * * * * * *

* * * * * * * * *

Explanation:

In this instance, we have constructed a star pyramid utilizing a nested for loop.

Loop Control Statements with Python for Loop

We will now explore different loop control statements that are utilized within Python's for loop.

1) break Statement

The 'break' statement within a 'for' loop halts the ongoing iteration permanently.

Example

Example

cars = ["Tata", "Honda", "Mahindra", "BMW"]

for brand in cars:

  if brand == "Mahindra":

    break # This break statement will stop iteration

  print(brand)

Output:

Output

Tata

Honda

Explanation:

In the preceding example, we utilized the break statement within the 'for' loop to terminate the iterations when the value of the current iteration is "Mahindra".

2) continue Statement

The 'continue' statement within a 'for' loop causes the program to bypass the current iteration and proceed directly to the subsequent one.

Example

Example

cars = ["Tata", "Honda", "Mahindra", "BMW"]

for brands in cars:

  if brands == "Mahindra":

    continue # this statement will stop iteration if Mahindra occurs, continue further

  print(brands)

Output:

Output

Tata

Honda

BMW

Explanation:

In this illustration, we utilized the continue statement to bypass the present iteration of the 'for' loop.

3) pass Statement

Within a 'for' loop, the 'pass' statement serves as a placeholder in Python. This indicates that it can be utilized when we want to include a line in our code, yet do not intend for it to execute any action at this moment, or we wish to reserve a spot for future code additions.

Example

Example

for n in range(1, 11):

  if n % 3 == 0:

      pass # this works as a placeholder

  else:

      print(n)

Output:

Output

1

2

4

5

7

8

10

Explanation:

In this illustration of the pass statement within a for loop, the pass statement serves as a temporary placeholder, signifying that additional code may be incorporated into the if-block at a later time.

4) else with for loop

The 'else' clause within a 'for' loop serves to deliver an output when the preceding condition is not fulfilled or is unattainable.

Example

Example

for i in range(1, 10):

  print(i)

else:

  print("Loop Finished")

Output:

Output

1

2

3

4

5

6

7

8

9

Loop Finished

Explanation:

In this instance, the else clause is executed following the conclusion of the 'for' loop.

Conclusion

The 'for' Loop in Python serves as an essential mechanism within the programming domain, facilitating numerous functionalities such as iteration and looping. Control statements, including continue, break, pass, and else, enhance the program's efficiency and provide better control over its execution flow.

Python for Loop FAQs

1. Does a 'for' loop in Python iterate over different data types?

Indeed, the For Loop in Python is capable of iterating through various data types, including Strings, Lists, Tuples, and Dictionaries.

2. Does indentation play any role in Python for loops?

Indeed, indentation is crucial in Python as it signifies whether a particular block of code is part of the current loop or not.

3. What are Control Statements in a For Loop in Python?

Control statements such as 'continue', 'break', 'pass', and 'else' serve to influence the execution and flow of a program.

4. Explain the differences between the 'for' loop and the 'while' loop.

  • For Loop: The 'for' loop in Python allows us to iterate over iterable objects, such as tuples, lists, dictionaries, and strings, until it reaches the termination of the sequence or the condition is fulfilled.
  • While Loop: The 'while' loop in Python allows us to repeatedly execute the block of code while the given condition remains true.

Input Required

This code uses input(). Please provide values below: