Looping Constructs in Python

Updated on May 20, 2019
Sam Shepards profile image

I'm a software developer with a great interest in data analysis and statistics.

Looping constructs in any programming language are used to perform a sequence of steps repeatedly for a given number of times. Python allows two types of loops – the for loop and the while loop. It is also possible to add a loop in another loop and create a nested loop in Python.

The For Loop

While iterating over a tuple or list, we can either use indices and write a traditional for loop that is similar to the one found in C/C++ or write a for-each-sequence loop similar to that in Java. Let us learn more about for loops.

Iterating Over Building Blocks of a Sequence

#!/usr/bin/python3
print("Printing letters of string in each line... ")
for cur in 'Hello World!':     
    print (cur)

rhymes = ['Mary','Had','A','Little','Lamb']
print("Printing words in the rhyme in each line...")
for word in rhymes:        
    print (word)

print ("...Reached the end...")

In the first for loop, we take the string ‘HelloWorld!’ sequence and iterate over it using iteration variable. In general, the syntax of this type of for loop can be expressed as:

for iter_var in sequence:
       # steps inside for loop.

The first two for loops show how letters in a string and words in a list representing a phrase are treated as individual building blocks of the sequence.

The output for the above program will be:

Printing letters of string in each line...
H
e
l
l
o
W
o
r
l
d
!
Printing words in the rhyme in each line...
Mary
Had
A
Little
Lamb
 ...Reached the end...

This type of for loop can be applied in case of a tuple or a dictionary as well. The code below demonstrates how to iterate over a dictionary considering the keys or key-value pairs as the building blocks of the sequence.

#!/usr/bin/python3

print("Iterating over a dictionary")
studentDict = {'firstName': 'john','lastName':'Smith', 'age': 29, 'studentId':415312}

print("Iterating using a key alone in for loop")
for key in studentDict:
    print("key: ", key, ", value: ", studentDict[key])

print("Iterating using key and value")
for foo,bar in studentDict.items():
    print("key: ", foo, ", value: ", bar)
print ("...Reached the end...")

In the first for loop, we iterate over the dictionary using key alone. In second for loop, both key and value are used as iteration variables to iterate over the items in the dictionary named "studentDict". Note that it is not mandatory to mention the name as ‘key’ and ‘value’ always in the for loop and to demonstrate it, we have used foo and bar.

Output for the above code will be:

Iterating over a dictionary
Iterating using a key alone in for loop
key:  firstName , value:  john
key:  studentId , value:  415312
key:  lastName , value:  Smith
key:  age , value:  29
Iterating using key and value
key:  firstName , value:  john
key:  studentId , value:  415312
key:  lastName , value:  Smith
key:  age , value:  29
...Reached the end...

Iterating Over Sequence Using Index and Range

This is similar to the for loops that we see in languages like C/C++/Java etc. Elements of a given sequence are accessed using index.

The range() function is used to return a range of values starting from zero as lower bound to the value mentioned as a parameter in the upper bound. It is possible to get a sub-range by mentioning a lower bound and upper bound.

For example, range(2,6) returns 2, 3, 4, 5 whereas range(3) will return 0, 1, 2. In the following code, we use range(len(rhymes)) to direct python to iterate over positions 0, 1, 2, till the rhymes[length – 1] and print the values.

#!/usr/bin/python3
rhymes = ['Mary','Had','A','Little','Lamb']

print("Printing each word in new line accessed by index.")
for index in range(len(rhymes)):
    print (rhymes[index])

The output for the above code will be:

Printing each word in new line accessed by index.
Mary
Had
A
Little
Lamb

The While Loop

The general syntax of while loop can be represented as follows:

while condition:
    # do these steps

It repeatedly executes the steps as long as the condition holds true. So, an infinite loop can be easily written using this while loop just like how we create it in C/C++/Java using:

test = 1
while test == 1:
    # do these steps infinite number of times

In the following program, we print numbers from 11 to 20 using a simple while loop.

#!/usr/bin/python3

print("Counting from 11 to 20")
count = 11
while count<=20:
    print(count)
    count = count + 1

The output of the above program will be as follows:

Counting from 11 to 20
11
12
13
14
15
16
17
18
19
20

Nested Loops

It is possible to nest a loop within another loop. Consider the following sample program. It is designed to print a number pyramid in the following manner:

1
1 2
1 2 3
1 2 3 … n 

#!/usr/bin/python3

# Program to print a number pyramid like:
for i in range(1,6):
    for j in range(1, i+1):
        print (j, end=" ")
    print("")

In the first for loop, we specify the range’s lower limit as 1 and upper limit as 5+1. In the second loop, we specify the range from 1 to i+1 for each line. Note that the print statement has a parameter named end=” “.

This is to direct the interpreter to print further outputs in the same line and all these outputs shall be separated using the special character shown. If the statement is changed to print (j, end=", "), all numbers will have a trailing comma. Output for the above program will be:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Loop Control Statements

Python offers three control statements:

  • Break statement – It terminates the loop statement and transfers the control outside the scope to the next statement following the loop.
  • Continue statement – It causes the loop to skip the remaining steps of the loop but continue with the next iteration.
  • Pass statement – It is often useful for debugging the code. Nothing really happens when the statement is executed.

Let us learn more about these statements with an example:

#!/usr/bin/python3
print('Printing letters in Welcome till letter l')
for letter in 'Welcome':
    if letter == 'l':
        break
    print (letter, end=", ")
    
print("")
print('Printing letters in welcome after omitting l')
for letter in 'Welcome':
    if letter == 'l':
        continue
    print (letter, end=", ")
print(" ")
print("Adding pass block when l is encountered")
for letter in 'Welcome':
    if letter == 'l':
        pass
        print(" ")
        print("Encountered pass block")
        print("Continue printing")
    print (letter, end=", ")

The output of the above code will be as follows:

Printing letters in Welcome till letter l
W, e,
Printing letters in welcome after omitting l
W, e, c, o, m, e, 
Adding pass block when l is encountered
W, e, 
Encountered pass block
Continue printing
l, c, o, m, e,

© 2019 Sam Shepards

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, turbofuture.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://turbofuture.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)