You are currently viewing Looping statements in Python

Looping statements in Python

Introduction

Iteration refers to running a block of code repeatedly, maybe several times. A loop is a type of programming construct used to implement iteration. We will go over the for loop, the while loop, and a couple of their usage scenarios in this article.

For loop

The Python for loop function is one of the simplest built-in functions to comprehend since it feels like we are just reading an English book. It’s that simple to grasp. We’ll go over most of the aspects of the for loop in this tutorial. We’ll demonstrate to you how to use it and, more importantly, when to use it, and how it could save a lot of time with a variety of examples so you can get an excellent understanding of how it interacts with the language. For loop could be used with any iterable thing it could be a list, string, array, tuple or dataframe, etc.

SYNTAX

for val in seq:  
conditions;  

Implementing For loop in a list

# CREATING A LIST
a = [1,1,9,10,7,11,9,10,18,3,5]

#CREATING AN EMPTY DICTIONARY TO STORE THE ELEMENTS AND THE NUMBER OF TIMES THEY
# ARE OCCURRING


occurrences = {}

# INITIALIZING A FOR LOOP TO ITERATE OVER EACH ELEMENT IN A LIST 

for i in a:

  if i in occurrences:
    occurrences[i] += 1;
  else:
    occurrences[i] = 1; #ELSE COUNT IT AS 1

for key, value in occurrences.items():
  print(“Element {0} is occuring {1} number of times”.format(key,value)); 

The output of the above program

Implementing a for loop in Dataframe to iterate over a column

import pandas as pd
df_dev = pd.read_csv(‘weisp_dev.csv’);
df_dev.head(3);
from collections import Counter

Sum = 0 

#USING FOR LOOP TO ITERATE OVER A COLUMN OF DATAFRAME TO FIND THE NUMBER OF ‘O’S IN IT
for i in range(len(df_dev[‘ner_tags’])):
  x = ‘O’;
  d = Counter(df_dev[‘ner_tags’][i]);
  Sum; 

  print(x,d[x]);
The output of the above program

TEMPORARY VARIABLES USAGE WITHIN THE LOOP

list = [[‘Pratyush’,80],[‘Akash’,85],[‘Neel’,97],[‘Sweta’,92],[‘Adyasha’,98],[‘Priyasha’,97],[‘Anuksha’,96],[‘Anwesha’,96]]

for name, marks in list:
  print(name,’obtained’,marks,’in exam’)
The output of the above program

NESTED FOR LOOP

A loop statement contained inside another loop statement is known as a “nested loop.” Nested loops are also known as “loops inside loops” for this reason.

for num1 in range(1,4):
  for num2 in range(1,4):
    print(“num1 is”,num1,”num2 is”,num2,”on multiplication we get”,num1*num2)
The output of the above program

USING FOR LOOP TO DO CHANGES IN A TXT FILE

Create a file named for.txt and paste the following content which is given down below

I,am,a,student,my,ambition,is,to,develop,a,model,that,helps,to,solve,real,world,problem,natural,calamities,
hunger,shortage,making,earth,a,better,place,to,live.
with open(‘/content/for.txt’) as f: 
  for line in f.readlines():
    line = line.replace(‘,’,’ ‘) #replacing the commas with spaces
print(line) #priniting the changes
f.close()

ACCESS INDEX IN FOR LOOP

The loop they are considered to be iterated when the loop is carried out. If an array is being iterated and the item’s index value is 5, then it is the 6th iteration (as array indices begin to count from zero). The above statement can be understood better if you just focus on the output of the following code.

Continents = [‘Asia’, ‘Africa’, ‘North America’, ‘South America’, ‘Antarctica’, ‘Europe’, ‘Australia’]
for index,values in enumerate(Continents): #ENUMERATE FUNCTION GIVES A COUNTER FOR THE LIST
  print(index,values)
The output of the above program

BREAK STATEMENT IN FOR LOOP

The break ends the loop prior to it having finished executing in accordance with the conditions set forth in it. 

In essence, if a loop is nested, the break command will halt the innermost loop. As we can see in the examples illustrated below:

Continents = [‘Asia’, ‘Africa’, ‘North America’, ‘South America’, ‘Antarctica’, ‘Europe’, ‘Australia’]
for i in Continents:
  if i == ‘South America’:
    break;
  print(i)

CONTINUE STATEMENT IN A FOR LOOP

For the current iteration of the loop only, the continue statement is employed to bypass the remaining lines of code. The loop does not end; rather, it continues with the following iteration.

The Continue statement or command just works in the reverse manner we saw in the examples above of break. The syntax mostly remains the same. Just focus on the output and understand the changes.

Continents = ['Asia', 'Africa', 'North America', 'South America', 'Antarctica', 'Europe', 'Australia']
for i in Continents:
  if i == 'South America':
    continue;
  print(i)

While loop

Now we will be discussing while loop another most frequently used command in programming. As long as a test expression (condition) is true, a chunk of code is iterated over in a while loop.

SYNTAX

while <condition>:
    <block of code> 

A few examples we will be looking at now are:

i = 0
while i <=3:
  print(‘count is increasing’)
  i += 1
print(‘end’)

Now I leave it up to you people to determine though the command says <=3, the message “count is increasing” is printed 4 times.

Advantages of Looping statement

  • It allows for the reuse of code.
  • By using loops, we may avoid writing the same code over and over.
  • We can iterate through the components of data structure architectures using loops (array or linked lists).

Conclusion

We learned about the for and while loops in this blog, as well as a couple of their implementations, but this isn’t the end; feel free to experiment and learn more. Without entering the realm of infinite recursion, you can attempt implementing nested while loops or working through some issues on your own. If there are any errors, please pardon me; I’m new to content writing and aspire to be a data scientist. Your helpful criticism and recommendations are greatly appreciated as I work to improve.