Python

Understand Loops in Python With Examples – Data Analysis

Understand Loops in Python With Examples – Data Analysis

This tutorial covers various ways to use loops in python with several practical examples. After reading this tutorial, you will be familiar with the concept of loops and will be able to apply them in real-world scenarios for data analysis.

What is Loop?

Loop is used to repeat a particular task multiple times until a specific condition is met. It is to automate repetitive tasks.

Types of Loops in Python

There are two types of loops in Python :

  1. For loop : This loop runs code for each item in a sequence. It’s useful when you already know how many times it needs to repeat.
  2. While loop : This loop runs code repeatedly until a specific condition is true. It’s useful when you don’t know the exact number of times it needs to repeat in advance.

For Loop

The syntax of a for loop in Python is as follows:


for item in sequence:
    # Code to be executed for each item

Example 1 : Suppose you are asked to print numbers from 1 to 9, increment by 2.

for i in range(1,10,2):
  print(i)

# Output
# 1
# 3
# 5
# 7
# 9

range(1,10,2) means starts from 1 and ends with 9 (excluding 10), increment by 2.

Example 2 : Suppose you are asked to run for loop on a list.

mylist = [30,21,33,42,53,64,71,86,97,10]
for i in mylist:
    print(i)

# Output
# 30
# 21
# 33
# 42
# 53
# 64
# 71
# 86
# 97
# 10

Example 3 : Suppose you need to select every 3rd value of list.

for i in mylist[::3]:
    print(i)

# Output
# 30
# 42
# 71
# 10

mylist[::3] is equivalent to mylist[0::3] which follows this syntax style list[start:stop:step]

How to create a new list in for loop

Suppose you want to create a new list containing only items from the original list that are between 0 and 10.

l1 = [100, 1, 10, 2, 3, 5, 8, 13, 21, 34, 55, 98]
new = [] #Blank list
for i in l1:
    if i > 0 and i <= 10:
        new.append(i)
print(new)

# Output : [1, 10, 2, 3, 5, 8]

It can also be done via numpy package by creating list as numpy array. See the code below.

import numpy as np k=np.array(l1) new=k[np.where(k<=10)]

How to Use For Loop on Pandas DataFrame

Create a sample pandas dataframe to explain examples in this tutorial.

import pandas as pd
np.random.seed(234)
df = pd.DataFrame({"x1" : np.random.randint(low=1, high=100, size=10),
                     "Month1" : np.random.normal(size=10),
                     "Month2" : np.random.normal(size=10),
                     "Month3" : np.random.normal(size=10),
                     "price"  : range(10)
                     })

Example 1: Multiple each month column by 1.2

for i in range(1,4):
    print(df["Month"+str(i)]*1.2)

range(1,4) returns 1, 2 and 3. str( ) function is used to covert to string.“Month” + str(1) means Month1.

Example 2 : Store computed columns in new data frame

import pandas as pd
newDF = pd.DataFrame()
for i in range(1,4):
    data = pd.DataFrame(df["Month"+str(i)]*1.2)
    newDF=pd.concat([newDF,data], axis=1)

pd.DataFrame( ) is used to create blank data frame. The concat() function from pandas package is used to concatenate two data frames.

Example 3 : Check if value of x1 >= 50, multiply each month cost by price. Otherwise same as month.

import pandas as pd
import numpy as np
for i in range(1,4):
    df['newcol'+str(i)] = np.where(df['x1'] >= 50,
                                   df['Month'+str(i)] * df['price'],
                                   df['Month'+str(i)])

In this example, we are adding new columns named newcol1, newcol2 and newcol3. np.where(condition, value_if condition meets, value_if condition does not meet) is used to construct IF ELSE statement.

Example 4 : Filter data frame by each unique value of a column and store it in a separate data frame

mydata = pd.DataFrame({"X1" : ["A","A","B","B","C"]})
for name in mydata.X1.unique():
    temp = pd.DataFrame(mydata[mydata.X1 == name])
    exec('{} = temp'.format(name))

The unique( ) function is used to calculate distinct values of a variable. The exec( ) function is used for dynamic execution of Python program. See the usage of string format( ) function below.

mystring= "Your Input"
"i am {}".format(mystring)

# Output
# 'i am Your Input'

Loop Control Statements

Loop control statements change execution from its normal iteration. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements.

  1. Continue statement
  2. Break statement

Continue Statement

When continue statement is executed, it skips the further code in the loop and continue iteration. In the code below, we are avoiding letters a and d to be printed.

for n in "abcdef":
    if n =="a" or n =="d":
       continue
    print("letter :", n)

# Output
# letter : b
# letter : c
# letter : e
# letter : f

Break Statement

When break statement runs, it breaks or stops the loop.

In this program, when n is either c or d, loop stops executing.

for n in "abcdef":
    if n =="c" or n =="d":
       break
    print("letter :", n)

# Output
# letter : a
# letter : b

For Loop with Else Clause

Using else clause with for loopis not common among python developers community.

The else clause executes after the loop completes. It means that the loop did not encounter a break statement.

The program below calculates factors for numbers between 2 to 10. Else clause returns numbers which have no factors and are therefore prime numbers:

for k in range(2, 10):
    for y in range(2, k):
        if k % y == 0:
            print( k, '=', y, '*', round(k/y))
            break
    else:
        print(k, 'is a prime number')

# Output
# 3 is a prime number
# 4 = 2 * 2
# 5 is a prime number
# 6 = 2 * 3
# 7 is a prime number
# 8 = 2 * 4
# 9 = 3 * 3

While Loop

While loop is used to execute code repeatedly until a condition is met. And when the condition becomes false, the loop stops and then the line immediately after the loop in program is executed.

The syntax of a while loop in Python is as follows:


while condition:
    # This code will continue executing as long as the condition is True

Example : The while loop below prints odd numbers less than 10.

i = 1  # Initialize i to 1
while i < 10:  # Loop continues until i is less than 10
    print("i: ",i)  # Print the current value of i
    i += 2  # Increment i by 2 (same as i = i + 2)

# Output
# i:  1
# i:  3
# i:  5
# i:  7
# i:  9

While Loop with If-Else Statement

If-Else statement can be used along with While loop. See the program below –

counter = 1
while (counter <= 5):
    if counter < 2:
        print("Less than 2")
    elif counter > 4:
        print("Greater than 4")
    else:
        print(">= 2 and <=4")
    counter += 1

The code iterates through numbers from 1 to 5. It prints “Less than 2” if the number is less than 2, “Greater than 4” if it’s greater than 4, else it prints “>= 2 and <=4”.

Suggested Articles

Leave a Reply

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