Control Flow Statements – For Loops in Python

For loop in Python, just like any other language, are used to repeat a block of code for a fixed number of times. For loop is yet another control flow statement since the control of the program is continuously transferred to the beginning of the for loop to execute the body of for loop for a fixed number of times.

While other languages contain conditions and increment expressions in the syntax of for loop, in Python, the iteration and incrementing value are controlled by generating a sequence. In this module, we will learn about Python for loops.

Become a Professional Python Programmer with this complete Python Training in Singapore!

Following is the list of all topics that we will cover in this module.

How to Use For Loops in Python

For loops in Python are used for sequential iterations for a certain number of times, that is, the length of the sequence. Iterations on the sequences in Python are called traversals.

Syntax of for loops in Python

Let us see the Python Syntax of For Loop with examples:

for a in sequence:
body of for

The following flowchart explains the working of for loops in Python:

As depicted by the flowchart, the loop will continue to execute until the last item in the sequence is reached. The body of the for loop, like the body of the Python while loop, is indented from the rest of the code in the program.

Go for this in-depth job-oriented Python Training in Hyderabad now!

Let us take a look at the Python for loop example for better understanding.

square = 1
numbers_list = [1,2,3,4,5,6,7]

for i in numbers_list:
square = i*i
print(“The square of”, i, “is”, square)

Output:
The square of 1 is 1
The square of 2 is 4
The square of 3 is 9
The square of 4 is 16
The square of 5 is 25
The square of 6 is 36
The square of 7 is 49

In the above example, we are calculating the squares of all elements present in the list of numbers that we have created, named ‘numbers_list’, using Python for loop. The variable i iterates from the beginning to the end of the Python List, and when the program enters the body of the loop, the square of each element is calculated using the variable i and stored in a variable named ‘square’.

Now that we understood how to write for loop in Python let us go ahead and take a step further and learn what range function in for loop.

Certification in Full Stack Web Development

The range() Function In Python For Loops

We can specify a particular range using an inbuilt Python function, named range(), to iterate the loop a specified number of times through that range.

Example:

range(10)

Note: The range here is not from 1 to 10 but from 0 to 9 (10 numbers).

Specifying start and stop points in the range() function:

Example:

range(3,7)

Note: Here, in this example, the starting point is 3 and the ending point is 7. So, the list will be generated from 3 to 6 (4 numbers).

Using Python for loops with the range() function:

Example:

We can simply use Python For loop with the range() function as shown in the example below.

For i in range(2,10):
print(i)

Output:
2
3
4
5
6
7
8
9

By default, the increment in the range() function when used with loops is set to 1; however, we can change or specify a particular increment by including a third parameter in the range() function, as illustrated in the following example:

For i in range(2,10,2)
print(i)

Output:
2
4
6
8

We have the perfect professional Python Course in Bangalore for you!

Get 100% Hike!

Master Most in Demand Skills Now !

Loop Interruptions in Python For Loops

  1. Break Statement

Just as in while loops, for loops can also be prematurely terminated using the break statement. The break statement will immediately terminate the execution of the loop and transfer the control of the program to the end of the loop.
Example:

# creating a list of numbers
number_list = [2,3,4,5,6,7,8]


for i in number_list:
print(i)
if i == 5:


break


Output:
2
3
4
5
  1. Continue Statement

Just as with while loops, the continue statement can also be used in Python for loops to terminate the ongoing iteration and transfer the control to the beginning of the loop to continue the next iteration.

number_list = [2,3,4,5,6,7,8]


for i in number_list:
if i == 5:
continue
print(i)


Output:
2
3
4
6
7
8

Note that the fifth iteration was interrupted as we have used the continue statement when the value of i is 5. Therefore, the control was passed to the beginning of the loop, and the program started executing the sixth iteration and did not print the value of i when it was 5.

Become a Full Stack Web Developer

Else in Python For Loops

For loop in Python can have an optional else block. The else block will be executed only when all iterations are completed. When break is used in for loop to terminate the loop before all the iterations are completed, the else block is ignored.
Example:

for i in range(1,6):
print(i)

else:
print(” All iterations completed”)

Output:
1
2
3
4
5

All iterations completed

Nested For Loop in Python

As the name suggests, nested loops are the loops that are nested inside an existing loop, that is, nested loops are the body of another loop.
Example:

for i in range(1,9,2):
for j in range(i):
print( i, end = ‘ ‘)
print()


Output:
1
3 3 3
5 5 5 5 5
7 7 7 7 7 7 7

Looking for Python Data Science Course All-in-1 Combo Training? Enroll now!

In the above example, we have used nested loops to print a number pyramid pattern. The outer loop is used to handle the number of rows in the pattern, and the inner loop or the nested loop is used to handle the number of columns in the pattern. Note that we have also used the third parameter in the range() function and have set the increment to 2, that is why the number in every column is incremented by 2.

Career Transition

Non-Tech to IT Associate | Career Transformation | AWS Certification Course - Intellipaat Reviews
Non Tech to DevOps Engineer Career Transition | Intellipaat Devops Training Reviews - Nitin
Upskilled & Got Job as Analyst After a Career Break |  Data Science Course Story - Shehzin Mulla
Successful Career Change after Completion of AWS Course - Krishnamohan | Intellipaat Review
Got Job Promotion After Completing Artificial Intelligence Course - Intellipaat Review | Gaurav
Intellipaat Reviews | Big Data Analytics Course | Career Transformation to Big Data | Gayathri

Difference between for and while loop in Python

Parameter For Loop While Loop
Format It allows initialization, condition checking, and iteration statements that are written on the top of the loop. It only allows initialization and condition checking at the top of the loop.
Declaration for(initialization; condition; iteration){ //body of ‘for’ loop} while ( condition) { statements; //body of loop}
Condition It iterates infinite time if no condition is given. It shows an error if no condition is given.
Initialization If initialization is once done in the “for” loop, it never is repeated. If initialization is done while condition checking, then it is required each time when the loop iterates itself.
Iteration Statement As the iteration statement is written at the top, it will execute only after all the statements are executed. The iteration statement can be placed anywhere in the syntax of the loop.

Reverse for loops in Python

We can reverse for loop in python in two ways. The first method is to use the reversed() function.

list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in reversed(list) :
   print(i)

The second method is using range(n,-1,-1)

list = ['Mon', 'Tue', 'Wed', 'Thu']
for i in range( len(list) - 1, -1, -1) :
    print(list[i])

The output will be

Thu
Wed
Tue
Mon

With this, we come to the end of this module in Python Tutorial. Now, if you want to know how you can use python for data science, you can go through this blog on Python Data Science tutorial.

Further, check out Intellipaat’s Python training to take your career to new heights. Also, check out our Python coding interview questions, which will help in cracking any Python interview.

Course Schedule

Name Date Details
Python Course 30 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 06 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 13 Apr 2024(Sat-Sun) Weekend Batch
View Details