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. The ‘for’ loop proceeds to the next step after each iteration is completed.
Syntax of the Python for Loop
It has the following syntax:
# 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 us see through a simple example to understand how the For Loop works in Python.
Example
# printing numbers using for loop
for i in range(1,7): #Here we have used for loop
print (i)
Output:
1
2
3
4
5
6
Explanation:
In the above example, we used a for loop with the range() function to print numbers ranging from 1 to 6.
Flowchart of the for Loop in Python
The following flowchart represents the working of a ‘for’ loop:
Step 1: The ‘for’ loop iterates over each item in the sequence.
Step 2: It will check whether the last item in the sequence has been reached; if not, the loop will return to the statement.
Step 3: If the final item in the sequence is reached, the loop will exit.
Examples of Python for Loop
We will now look at some basic examples of Python for loop:
Printing Elements from a List or Tuple
Lists and Tuples are the data structures used in Python to store multiple items in a single variable. We can use the ‘for’ loop to iterate through each element of these sequential data structures.
Let us take a look at the following 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:
Tata
Honda
Mahindra
Suzuki
BMW
Explanation:
In this example, we are given a list. We used the ‘for’ loop to iterate through element of the list and printed them.
Python Program to Print Factorial of a Number
We will now take a look at an example to print the factorial of a number. For this Python program, we will use the ‘for’ loop to iterate through each number from 1 to that number and add them to return the factorial of the number.
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:
Enter a Number: 5
5! = 120
Explanation:
In this example, we have used the ‘for’ loop to iterate through the range from 2 to that number and multiply the value from the current iteration with the initialized factorial value. As a result, we calculated the factorial of the number.
Nested for Loop
In Python, a nested ‘for’ loop refers to a ‘for’ loop placed inside the body of another ‘for’ loop. We generally use this structure while iterating over multi-dimensional data structures, generating patterns, or performing operations that requires multiple levels of iteration.
Syntax:
Nested for loop has the following syntax:
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)
Let us now take a look at some examples to understand the working of nested for loop.
Printing the Elements of the Matrix
We will now see an example to print the elements of a 3×3 Matrix using the nested for loop.
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:
Given Matrix:
13 4 27
22 16 8
5 11 19
Explanation:
In the above example, we are given a 3×3 matrix. We used the nested for loop to iterate through the rows and columns in the given matrix and print the elements.
Pyramid Pattern using Nested for Loop
We will now take a look at the following program to create a Pyramid using the Nested for Loop.
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:
Enter number of rows: 5
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
Explanation:
In this example, we are have created a star pyramid using the nested for loop.
Loop Control Statements with Python for Loop
We will now look at various loop control statements used in Python’s for loop.
1) break Statement
The ‘break’ statement in the ‘for’ loop permanently stops the current iteration.
Example
cars = ["Tata", "Honda", "Mahindra", "BMW"]
for brand in cars:
if brand == "Mahindra":
break # This break statement will stop iteration
print(brand)
Output:
Tata
Honda
Explanation:
In the above example, we used the break statement in the ‘for’ loop to stop the iterations when the current iteration value is “Mahindra”.
2) continue Statement
The ‘continue’ statement in the ‘for’ loop skip the current iteration and move to the next.
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:
Tata
Honda
BMW
Explanation:
In this example, we used the continue statement to skip the current iteration of the ‘for’ loop.
3) pass Statement
In ‘for’ loop, the ‘pass’ statement in Python is used as a placeholder. It means that we can use it when we need to write something in our code but don’t want it to do anything or want to leave space to write something in the future.
Example
for n in range(1, 11):
if n % 3 == 0:
pass # this works as a placeholder
else:
print(n)
Output:
1
2
4
5
7
8
10
Explanation:
In this pass statement in for loop example, the pass statement is a placeholder indicating that a piece of code can be added in the if-block in the future.
4) else with for loop
The ‘else’ statement in the ‘for’ loop is used to provide an output when the previous condition is not met or cannot be achieved.
Example
for i in range(1, 10):
print(i)
else:
print("Loop Finished")
Output:
1
2
3
4
5
6
7
8
9
Loop Finished
Explanation:
In this example, the else statement is execute after the completion of the ‘for’ loop.
Conclusion
The ‘for’ Loop in Python is a very crucial construct in the programming world, which helps in various aspects such as iteration and looping. Control statements like continue, break, pass and else make the functioning of the program more controlled and efficient.
Leave a Reply