Loops in python explained with simple example

Python provides mainly two looping constructs which allows programmer to execute a section of code to repeat multiple number of times.

The while loop provides a way for programmers to code general loops whereas the for loop provides the option to code using items in a sequence or other iterable objects.

Loops in Python

Let’s have a look into loops in python in detail.

While loop

This is the most general iteration construct supported by python which repeatedly executes a series of code until a certain condition keeps on evaluating to true.

Syntax

while condition:       # Loop condition to be checked everytime
    statements    # Loop body
else:             # Optional else will be executed if above loop exits without a break
    statements    # Run if didn't exit loop with break

For loop

The for loop in python is a generic iterator which supports stepping through some iterable object in a sequential manner. It works on all kind of iterable objects such as strings, list, tuples etc.

Syntax

for item in object:         # Assign object item to variable item
    statements              # Loop body
else:                       # Optional else will be executed if above loop exits without a break
    statements              # Run if didn't exit loop with break

Nested loops

Python supports nested loops which means one loop (for, while) could be used inside any other (for, while) loop. There is no restriction of types of loop inside other type of loop and any loop could be placed inside any other loop in any number of times.

Loop control construct

There are following types of loop control construct available in python.

  • break – This breaks the closest enclosing loop’s execution immediately and control is jumped to the next statement after the closest enclosing loop.
  • continue – This skips the current iteration of the closest enclosing loop and immediately jumps the control to top of the closest enclosing loop.
  • pass – This does nothing and could be seen as empty statement which might be needed for syntax purpose.

Loop else construct

Till now whatever loop construct we discussed in python are basically quite similar to other programming languages like C, Java loop constructs. However, in Python there is a loop else construct also which gets executed if the loop body never gets executed or executed without encountering break.

This construct along with break is very useful to eliminate need of a certain state or condition (commonly known as status flag) needed by other programming language.

Let’s have a look into some examples to understand the usage of above constructs.

index = 0
while (index < 5):
    index += 1
    if index == 3:
        print ("skipping iteration -- ", index)
        continue
    print ("loop iteration - ", index)
else:
    print ("This should be printed as no break encountered")
    
index = 0
while (index < 5):
    index += 1
    print ("loop iteration - ", index)
    if index == 2:
        break;
else: # will be executed only if index == 2 never becomes true.
    print ("This should not be printed as no break encountered")

animals = ['Dog', 'Cat', 'Tiger', 'Crow']
for animal in animals:
    if animal == 'Crow':
        pass
    else:
        print ('Found 4 legged animal -- ', animal)

for x in ['hi', 'hello', 'bye']:
    print (x, ' Everyone !!')

s = 'India'
for c in s:
    print(c)

D = {'a': 1, 'b': 2, 'c': 3}
for key in D:
    print (key, ":", D[key])

for (key, value) in D.items():
    print(key, ':', value)

for (a, b, c) in [(1, 2, 3), (4, 5, 6)]:
    print (a, b, c)

# nested loop example
dictionary = ['Hi', 'Hello','bye', 'how', 'are', 'you']
search_items = ['Hi', 'who', 'how']

for item in search_items:
    for word in dictionary:
        if item == word:
            print (item, " is found !!")
            break
    else:
        print (item, " is not found !!")

Let’s look into the output of the above program.

loop iteration -  1
loop iteration -  2
skipping iteration --  3
loop iteration -  4
loop iteration -  5
This should be printed as no break encountered
loop iteration -  1
loop iteration -  2
Found 4 legged animal --  Dog
Found 4 legged animal --  Cat
Found 4 legged animal --  Tiger
hi  Everyone !!
hello  Everyone !!
bye  Everyone !!
I
n
d
i
a
a : 1
b : 2
c : 3
a : 1
b : 2
c : 3
1 2 3
4 5 6
Hi  is found !!
who  is not found !!
how  is found !!

Leave a Reply

Your email address will not be published. Required fields are marked *