Introduction

Python provides following types of loops to handle looping requirements

  • while loop
  • for loop

 

while loop

While Loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. Using else statement with while loops, while loop executes the block until a condition is satisfied. The else clause is only executed when while condition becomes false.

#1 while loop
count = 0
while (count < 3):	 
  count = count + 1
  print("Hello") 

# Output
Hello
Hello
Hello

#2 Combining else with while 
count = 0
while (count < 3):	 
  count = count + 1
  print("Hello") 
else: 
  print("Welcome") 
  
  
# Output
Hello
Hello
Hello
Welcome

#3 Single statement while block
count = 0
while (count == 0): print("Hello")

 

for loop

For loops are used for sequential traversal. For example

#1 Iterating over a list 
l = ["List1", "List2", "List3"] 
for i in l: 
  print(i) 
  
# Output
List1
List2
List3
  
#2 Iterating over a tuple 
t = ("T1", "T2", "T3") 
for i in t: 
  print(i) 

# Output
T1
T2
T3
  
#3 Iterating over a String 
s = "String"
for i in s : 
  print(i) 

# Output
S
t
r
i
n
g
  
#4 Iterating over dictionary 
d = dict() 
d['xyz'] = 123
d['abc'] = 345
for i in d : 
  print("%s %d" %(i, d[i])) 
  
# Output
xyz 123
abc 345

 

We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length. We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1 if not provided.

# Iterate over the list using index
genre = ['pop', 'rock', 'jazz']

for i in range(len(genre)):
  print(genre[i])

 

We can also combine else statement with for loop like in while loop. But as there is no condition in for loop based on which the execution will terminate so the else block will be executed immediately after for block finishes execution.

digits = [0, 1, 5]

for i in digits:
  print(i)
else:
  print("No items left!")
  
# Output
0
1
5
No items left!

 

Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

  • break
  • continue
  • pass
# 1 Prints all letters except 'e' and 'd' 
for letter in 'england': 
  if letter == 'e' or letter == 'd': 
    continue
  print (letter)
  
# 2 Example  
for letter in 'england': 
  # break the loop as soon it sees 'e' or 'd'
  if letter == 'e' or letter == 'd': 
    break
  print (letter)

 

We use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.

# An empty loop 
for letter in 'loop': 
  pass