My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Loops in Python

Odhiambo Brandy's photo
Odhiambo Brandy
·Jan 11, 2022·

6 min read

Loops In Python

Introduction

In Python there are two loops which are commonly known that is:

  • while loop
  • for loop

let us look at the two loops in detail.

While Loop

The while loop is like a repeated if statement. The code is executed over and over again, as long as the condition is True its syntax is

while condition :
    expression

Basic Examples of while Loop

Example 1:

x = 10
while x < 1 :
    print(x)
    x = x - 1

You can suggest the number of prints out from this example.

Example 2:

# Initialize num
num = 8
# Code the while loop as long as num is not equal to 0
while offset > 0:
    print("correcting...")
    offset = offset-1
    print(offset)

Note the following output will be given

correcting...
7
correcting...
6
correcting...
5
correcting...
4
correcting...
3
correcting...
2
correcting...
1
correcting...
0

Add conditionals

Take an instance when working with negative values within the while loop, the while loop will never terminate when the condition is given is while num > 0 and the incrementation is num = num-1.This loop will continue running since Zero will never be reached.

For this Instance adding conditional statemennt within a while loop is taken into considerartion.

Example:

# Initialize offset
offset = -6
# Code the while loop
while offset != 0 :
    print("correcting...")
    if offset > 0:
      offset = offset - 1
    else : 
      offset =offset +1   
    print(offset)

For Loop

Here is another loop used in python. the syntax for a for loop is:

 for var in exp:
    expression

As usual, you simply have to indent the code with 4 spaces to tell Python which code should be executed in the for a loop.

Example:

# sizes list
sizes = [11.25, 18.0, 20.0, 10.75, 9.50]
# Code the for loop
for size in sizes:
    print(size)

Using a for loop to iterate over a list only gives you access to every list element in each run, one after the other. If you also want to access the index information, so where the list element you're iterating over is located, you can use enumerate().

Example:

# sizes list
sizes = [11.25, 18.0, 20.0, 10.75, 9.50]

# Change for loop to use enumerate() and update print()
for index , a in enumerate(sizes) :
    print("index" + str(index) + ":" + str(a))

Update the first index to start from 1 by doing this to the printed index value str(index+1)

Loop over list of lists

Given a list of list like this

# heights list of lists
heights = [["mum", 11.25], 
         ["dad", 18.0], 
         ["brother", 20.0], 
         ["sister", 10.75], 
         ["uncle", 9.50]]

Use the looping creteria shown below to loop through your list of lists

for space in house:
    print( "the " + space[0] + ' is ' + str(space[1]) + ' sqm ')

Given that the values you are working with are float you can use the following format to loop through your list of lists

for x, y in heights:
    print(x + ' is ' + str(y) + ' height ')

Loops Data Structure

Dictionary

Dictionary is a data structure that stores values in form of keys and values as shown below.

data = {'population': 59.83, 'capital': 'Rome', }

Having a dictionary data structure you may want to loop through the value to get all the key and corresponding values as output we use the item() method and a for a loop. like this

for key,value in data.item():
    print(key + "Has the value" + str(value))

#or
for k,v in data.item():
    print(key + "Has the value" + str(value))

when you omit to call the item() method on the dictionary variable python shell will raise an error. So it is so important to call the item() method.

Numpy

NumPy is the most important Python module for scientific computing. NumPy arrays make it easier to do complex mathematical and other operations on massive amounts of data.

To use this package you have to do import this package as np

import NumPy as np

And use the package as shown below

# Create list of values
values = [180, 215, 210, 210, 188, 176, 209, 200]
# Create a numpy array from values: np_value
np_value = np.array([value])

When printing the values from the Numpy array we use a for loop as shown

for val in age:
    print(str(val) + " age")

To get every element of an array we use np.nditer() function with its input as the array you want to iterate over.

for val in np.nditer(value):
    print(val)

Pandas Data Frame

pandas is a data manipulation and analysis software package for the Python programming language.

Pandas DataFrame is a fully heterogeneous two-dimensional size-mutable tabular data format with labeled axes (rows and columns).

To use pandas data frame you have to import the package pandas as pd as shown

import pandas as pd

Now lets import the existing CSV file

# Import the statistics.csv data: statistics
statistics = pd.read_csv('statistics.csv', index_col=0)

If we want to access the column name in the CSV file imported we will use a basic for loop as shown

for val in statistics:
    print(val)

To iterate over the row data in the pandas CSV file we are using iterrows() method. This will specify the row label and the required data. It is done as shown below

for lab,row in statistics.iterrows():
    print(lab)
    print(row)

it is also possible to subset the CSV data been looped through.For instance lets loop through the data to display the Period row in the statistics.

for lab,row in statistics.iterrows():
    print(lab + ":" + row["Period"])

#converting row data to string
for lab, row in statistics.iterrows() :
    print(lab + ": " + str(row['Period']))
  • Adding a column to the existing data

Within the for loop you can also do manipulation like adding a column to the existing data.For instance lets loop through the statistics data,create a new row and assign it the lenght of data in the period row.

for lab,row in statistics.iterrows():
    statistics.loc[lab,"length"] = len(row["Period"])
print(statistics)

#Printing the data on a newly created row to uppercase of the exixting row
for lab,row in statistics.iterrows():
    statistics.loc[lab,"PERIOD"] = row["Period"].upper()

when you do a printout of the above code you will see the newly created row with assigned data.

You can also do the above manipulation without a for loop but by using the method apply() like this

statistics["length"] = statistics["Period"].apply(len)
print(statistics)

# Changing data to uppercase
statistics["PERIOD"] = statistics["Period"].apply(str.upper)
print(statistics)