Home  >  Blog  >   Python

Loops in Python

Rating: 4
  
 
3826
  1. Share:
Python Articles

Introduction

‘For’ loops in Python are used for iterating over a sequence. The sequences can vary from being list, tuple or dictionary. The ‘for’ loop can be used to iterate once for each item of the list, tuple, etc. Indexing is not necessary for any variable in case of the ‘for’ loop.

 

Use of the Python

Here is an example demonstrating the use of the Python.

Code:

Program = ["Python", "Ruby", "C"]
for x in Program:
print(x)

Output:

Python Ruby C

If you want enrich your career and become a professional in python, then visit Mindmajix - a global online training platform : "python course"   This course will help you to achieve excellence in this domain

 

MindMajix YouTube Channel

What is ‘for’ loop in Python?

‘for’ loop in Python is used for iterating over a sequence or any other objects which are iterable. Whenever the iteration is done over any sequence, the process is called traversal.

Syntax of ‘for’ loop

For val in sequence:
Body of for

In this syntax, ‘val’ is the variable which accesses the value of each item of the sequence. The Looping will be done until all items of the sequence are iterated. Indentation is used to separate the block of code of ‘for’ loop from the rest of the code

Flowchart of ‘for’ loop in Python 3

img

As represented by the flowchart, the loop is exited if all the items have been processed. If they are not, then the loop is continued until all the items have been processed.

Example of Python ‘for’ loop

Code:

numbers = [5, 2, 3, 7, 1, 9]
sum = 2
forval in numbers:
sum = sum+val
print("The sum is", sum)

Output:

Here is an example of the ‘for’ loop.

The sum is 29

[Related Page: Introduction To Python]

The range() function (small description with one example)

Generation of sequence is possible along with the usage of ‘range()’ function. It is also possible to define the stop, start, and step size of this function. The format of specifying them is ‘range(start,stop,step size)’.

Checkout Python Tutorial

print(range(5))

Through this, we will simply get the range.

range(0, 5)

If we require the result in the form of the list, it can be done by forcibly using the list function.

Code:

print(list(range(5)))

Output:

[0, 1, 2, 3, 4]

‘for’ loop with ‘else’ (small description with one example)

The ‘else’ block can also be used along with python ‘for’ loop list. This block is optional and is executed only after all the items of the python ‘for’ loop list exhaust. 

‘break’ statement is used for disrupting the normal flow of the ‘for’ loop. In this case, the ‘else’ part of the loop will be ignored, and if there will be no break of ‘for’ statement, then the ‘else’ part will execute.

Code:

sequence = [0, 1, 2, 3, 4]
for i in sequence:
print(i)
else:
print("No element left.")
Output:
0
1
2
3
4
No element left.

[Related Article: Regular expression operations]

The break Statement (small description with one example)

Break statement is used to disrupt the normal flow of the ‘for’ or ‘while’ loop and in order to exit it.

Code:

count = 1
while True:
print(count)
count += 2
if count >= 5:
break
Output:
1
3

The continue Statement (small description with one example)

The ‘continue’ statement is used to continue the normal flow of the loop after meeting the argument. The ‘python if’ statement is used to specify the condition.

Code:

for i in range(1,10):
if i == 3:
continue
print (i)
Output:
1
2
4
5
6
7
8
9

Nested Loops (small description with one example)

It is also possible to nest loops in Python.

Code:

for x in range(1, 5):
for y in range(1, 5):
print (x, y, x*y)

Output:

1 1 1
1 2 2
1 3 3
1 4 4
2 1 2
2 2 4
2 3 6
2 4 8
3 1 3
3 2 6
3 3 9
3 4 12
4 1 4
4 2 8
4 3 12
4 4 16

Recursion (small description with one example)

Recursion is possible in Python, which means that the function can call itself. This is useful when we have the data and we have to loop through it to get the desired result.

Code:

deftri_recursion(x):
if(x>0):
result = x+tri_recursion(x-1)
print(result)
else:
result = 0
return result
print("Recursion Example Results")
tri_recursion(5)

Output:

Recursion Example Results

1
3
6
10
15

Python ‘While’ Loop (Introduction)

The ‘while’ loop in Python is used to iterate some code until the condition remains true. This Loop is helpful when we do not know how long we will have to iterate the block of code.
Syntax of the ‘while’ loop

In the case of ‘while loop in Python’, an expression is defined first. If the expression is found to be true, then only the ‘while’ loop is iterated.

The iteration is continued until the expression is found false.

The syntax of the ‘while’ loop is as follows:

whiletext_expression
body of while

The body of the ‘while’ loop is defined through an indented block. The first indented block encountered determines the end of the body of the ‘while’ loop.

Flowchart of ‘while’ loop

As you can see in the chart, if the condition is found to be false, then the loop is exited. In case the condition is found to be true, it is executed again and again until the outcome becomes false.

Example: Python while Loop

Here is an example of the usage of ‘while’ loop.

Code:

n = 5
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)

Output:

The sum is 15

Using else statement with while loops (small description with one example)
Just like Python ‘for’ loop, we can also use the ‘else’ block with the ‘while’ loop. The ‘else’ block will be executed only after the condition of the ‘while’ loop is false. Understanding ‘for’ loops in python will help you with other aspects of Python as well.

Frequently Asked Python Interview Questions & Answers

‘Break’ statement can be used to terminate the ‘while’ loop.

Code:

coding = 0
while coding < 3:
print("completing loop")
coding = coding + 1
else:
print("completing else")
Output:
completing loop
completing loop
completing loop
completing else

Single statement while the block

If the ‘while’ block consists of a single statement, then the whole loop can be written in a single statement.

count = 0
while (count == 0): print("Python program

It is not beneficial to use this format as it may result in infinite loops and the user may have to forcefully terminate it.

Usage of loops in Python:

Here is why the loops are used in Python:

  • Generally, we have to execute the statements sequentially. Hence, the first statement is executed first and the last one is executed last.
  • Loops allow us to execute a block of code a number of times.
  • A statement or a group of statements can be executed multiple times without any inconvenience.

if you are interested learn python and build a career in it? Then check out our python training near your cities

Python Training ChennaiPython Training New YorkPython Training in BangalorePython Training in Dallas

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.

 

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!
Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Python TrainingMar 30 to Apr 14View Details
Python TrainingApr 02 to Apr 17View Details
Python TrainingApr 06 to Apr 21View Details
Python TrainingApr 09 to Apr 24View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read more
Recommended Courses

1 / 15