Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

How Many Types of Loops Are Used in Python

Published On: October 20, 2022

What Do You Mean by Python Loops?

Statements are run in a sequential fashion in Python. This means that if our code consists of multiple lines of code, then the execution will begin at the first line, then move on to the second line, and so on.

On the other hand, there will be situations in which we would want a section of code to run multiple times until a certain condition is satisfied. We are able to accomplish this goal by using loop statements.

The following categories of loops are available to users of the Python programming language for use in meeting various looping requirements: Python gives you three different options for carrying out the loops. Although all of the methods offer comparable fundamental functionality, they differ in the syntax they use and the amount of time they spend checking conditions.

The Programming Language Python’s Loops Used in General

Loops are a powerful tool in Python that may be used to address a wide variety of challenging situations. You may probably run across issues that require you to conduct an action multiple times until a certain condition is satisfied (the while loop is the most effective solution for this kind of issue), or issues that demand you to carry out an action on a number of different things (for loop works best here).

Python’s While Loop

A while loop is a programming construct in Python that allows a block of instructions to be executed continuously until a certain condition is met. And when the condition is no longer met, the line of code that is located just after the loop in the program is the one that is carried out

Syntax :while expression:    statement(s)

Following a coding construct, all of the statements that are indented by the same amount of character spaces are regarded to be a single unit of code and are therefore referred to as a block. Indentation is the means by which Python groups together individual statements. Illustration:# while loopcount = 0while (count < 4):  count = count + 1print(“Good Morning”) Ouput :Good MorningGood MorningGood Morning

The while loop, in contrast to the for loop, does not iterate over the sequence being processed. In order to determine the condition, it employs comparison operators and booleans.

The use of the else statement in conjunction with while loops

As was just mentioned, the while loop will continue to run the block until the given condition is met. The statement that comes directly after the loop will be carried out when the condition is found to be untrue.

Only in the event that your while condition is satisfied will the else clause be carried out. If you leave the loop in the middle of its execution or if an exception is thrown, it won’t be carried out.

If else like this:

if condition:

    # execute these statements

else:

    # execute these statements

and while loop like this is similar

while condition :

   # execute these statements

else:

     # execute these statements

Illustration For Else Statement

# combining else with while

count = 0

while (count < 4):

    count = count + 1

    print(“Good Morning”)

else:

    print(“In Else Block”)

Output :

Good Morning

Good Morning

Good Morning

In Else Block

Single Statement While Block

In the same way as with the if block, if the While block only contains one statement, we can declare the complete loop in a single line, as demonstrated in the following example :

Python program to illustration

# Single statement while block

count = 0

while (count == 0): print(“Good Morning”)

It is recommended that you do not use this type of loop since it is an infinite loop that never ends, the condition is always met, and you have to forcibly terminate the compiler.

Python’s For Loop notation

In order to perform sequential traversal, for loops are utilized. One example might be “traversing” a list, string, or array, among other examples. There is no equivalent to the for loop seen in C in Python; specifically, for (i=0; in; i++). There is a loop called “for in” that is quite similar to loops called “for each” in other programming languages. Let’s go over the steps for using a for-in loop to perform sequential traversals.

Syntax:

for iterator_var in sequence:

    statements(s)

It is possible to iterate over a range with it, together with other iterators.

Python program For illustration

# Iterating over range 0 to n-1

n = 5

for i in range(0, n):

    print(i)

Output :

0

1

2

3

4

Illustrations with List, string, Tuple, and dictionary iteration using “For Loops”

Illustration

# Iterating over a list

print(“List Iteration”)

l = [“good”, “morning”, “folks”]

for i in l:

    print(i)

# Iterating over a tuple (immutable)

print(“nTuple Iteration”)

t = (“good”, “morning”, “folks”)

for i in t:

    print(i)

# Iterating over a String

print(“nString Iteration”)

s = “Good”

for i in s:

    print(i)

# Iterating over dictionary

print(“nDictionary Iteration”)

d = dict()

d[‘xyz’] = 321

d[‘abc’] = 543

for i in d:

    print(“%s  %d” % (i, d[i]))

# Iterating over a set

print(“nSet Iteration”)

set1 = {1, 2, 3, 4, 5, 6}

for i in set1:

    print(i),

Output:

List Iteration

good

morning

folks

Tuple Iteration

good

morning

folks

String Iteration

G

o

o

d

Dictionary Iteration

xyz  321

abc  543

Iterating by the index of sequences:

Another method for iterating sequences is to use the index of the items in the sequence. The most important step is to figure out how long the list is and then proceed to iterate over the sequence while keeping the length of the list in mind.

Illustration:

Iterating by index

list = [“Good”, “Morning”, “Folks”]

for index in range(len(list)):

    print list[index]

Output :

Good

Morning

Folks

Using Else Statement With For Loops:

In the same way that we can combine while statements with for loops, we can also combine else statements with for loops. However, because the for loop does not contain a condition on the basis of which the execution will be terminated, the otherwise block will be performed as soon as the for block has completed its execution.

The following illustration will show you how to perform this :

Illustration :
Combining else with for
list = [“Good”, “Morning”, “Folks”]
for index in range(len(list)):
    print (list[index])
else:
    print (“Inside Else Block”)
Output :
Good
Morning
Folks
Inside Else Block

Nested Loops

It is possible to employ one loop within another loop when working with the Python programming language. The following part provides a few illustrations to further clarify the topic.

The syntax for this is as follows :

for iterator_var in sequence:

   for iterator_var in sequence:

       statements(s)

       statements(s)

The following is an example of the Python programming language’s syntax for the statement that creates a nested while loop :

while expression :

   while expression:

       statement(s)

       statement(s)

One last thing to mention about nesting loops is that it is possible to put any kind of loop inside of any other kind of loop. As an illustration, a while loop might be contained within a for loop, or vice versa.

Illustration :
nested for loops in Python
from __future__ import print_function
for i in range(1, 6):
    for j in range(i):
        print(i, end=’ ‘)
    print()
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Loop Control Statements

The execution of the loop is altered from its typical order by the control statements. When the execution of a program exits a scope, all automated objects that were generated while the execution was in that scope are deleted. The following are control statements that are supported by Python.

Continue Statement :

It takes control back to where it was before the loop was executed. Prints all letters except ‘o’ and ‘n’ for letter in ‘goodmorningfolks’:     if letter == ‘o’ or letter == ‘n’:         continue    print (‘Current Letter :’, letter)   var = 10 Output:Current Letter : gCurrent Letter : dCurrent Letter : mCurrent Letter : rCurrent Letter : iCurrent Letter : gCurrent Letter : fCurrent Letter : lCurrent Letter : kCurrent Letter : s

Breaking Statement:

It loses control from the loop.

Illustrationfor letter in ‘goodmorningfolks’:

    # break the loop as soon it sees ‘o’

    # or ‘n’

    if letter == ‘o’ or letter == ‘n’:

         break

print ‘Current Letter :’, letter

Output :Current Letter : o

Pass Statement :

Pass statements are used for creating empty loops. Additionally, empty control clauses, functions, and classes are handled by the pass function.

Illustration :
# An empty loop
for letter in ‘goodmorningfolks’:
    pass
print ‘Last Letter :’, letter
Output :
Last Letter : s

How does Python’s for loop function internally?

You should already have a working knowledge of Python Iterators before moving on to this section.

Let’s first look at what a straightforward for loop looks like.

Illustration # A simple for loop examplecolours = [“red”, “orange”, “blue”]For colours in colours: print(colours) Outputredorangeblue

We can see that the for loops traverse over the iterable object colour, which is a list, in this particular example. Iterable objects include the likes of lists, sets, and dictionaries, however, an integer object does not qualify as an iterable object.

It is possible to iterate over any iterable object using for loops (example: List, Set, Dictionary, Tuple or String).

Let’s take a closer look at what’s going on behind the scenes here with the help of the example that was just presented.

Using the iter() function, turn the list that can be iterated into an object that can be iterated.

Execute a while loop with no end condition, and only break out of it if the StopIteration flag is triggered.

Inside the try block, we use the next() function to retrieve the next element of the colour  array.

Following the retrieval of the element, we carried out the procedure that was intended to be carried out with the element. (i.e print(colour))

colours = [“red”, “orange”, “blue”]

# Creating an iterator object

# from that iterable i.e colours

iter_obj = iter(colours)

# Infinite while loop

while True:

  try:

    # getting the next item

    colour = next(iter_obj)

    print(colours)

  except StopIteration:

    # if StopIteration is raised,

    # break from loop

    break

Output

red

orange

blue

Hence we discussed all the types of loops and their functions.
Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.