
If we want to execute a group of statements multiple times then we should go for Iterative statements.
Here, we will discuss 4 types of Python Loop:
- Python For Loop
- Python While Loop
- Python Loop Control Statements
- Nested For Loop in Python
While Loop:
A while loop in python iterates till its condition becomes False. In other words, it executes the statements under itself while the condition it takes is True.
Syntax :
while expression: statement(s)
Python program to illustrate
while loop
Ex: count = 0 while (count < 3): count = count + 1 print("Hello Shishir") output Hello Shishir Hello Shishir Hello Shishir
Using else statement with while loops: As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
If else like this:
if condition: # execute these statements else: # execute these statements
and while loop like this are similar while condition: # execute these statements else: # execute these statements
count = 0
while (count < 3):
count = count + 1
print(“Hello Shishir”)
else:
print(“In Else Block”)
Output:
Hello Shishir
Hello Shishir
Hello Shishir
In Else Block
Single statement while block: Just like the if block, if the while block consists of a single statement the we can declare the entire loop in a single line as shown below:
count =0
while(count ==0): print("Hello Shishir")
for loop:
If we want to execute some action for every element present in some sequence(it may be string or collection)then we should go for for loop.
Syntax: for iterator_var in sequence: statements(s)
Python program to illustrate
Iterating over range 0 to n-1
n = 4 for i in range(0, n): print(i) Output : 0 1 2 3
#Python program to illustrate #Iterating over a list print("List Iteration") l = ["shishir", "kant", "singh"] for i in l: print(i) #Iterating over a tuple (immutable) print("\nTuple Iteration") t = ("hishir", "kant", "singh") for i in t: print(i) #Iterating over a String print("\nString Iteration") s = "Shishir" for i in s : print(i) #Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i])) Output: List Iteration shishir kant singh Tuple Iteration shishir kant singh String Iteration S h i s h i r Dictionary Iteration xyz 123 abc 345
Iterating by index of sequences: 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.
#Iterating by index list = ["shishir", "kant", "singh"] for index in range(len(list)): print list[index] Output: shishir kant singh
Using else statement with for loops: 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.
#combining else with for list = ["shishir", "kant", "singh"] for index in range(len(list)): print list[index] else: print "Inside Else Block" Output: shishir kant singh Inside Else Block
Nested Loops: Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax: for iterator_var in sequence: for iterator_var in sequence: statements(s) statements(s)
The syntax for a nested while loop statement in Python programming language is as follows:
while expression: while expression: statement(s) statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.
#nested for loops in Python from __future__ import print_function for i in range(1, 5): for j in range(i): print(i, end=' ') print() Output: 1 2 2 3 3 3 4 4 4 4
Loop 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.
Continue Statement: It returns the control to the beginning of the loop.
#Prints all letters except 's' and 'i' for letter in 'shishirkantsingh': if letter == 'e' or letter == 's': continue print 'Current Letter :', letter var = 15 Output: Current Letter : h Current Letter : h Current Letter : r Current Letter : k Current Letter : a Current Letter : t Current Letter : n Current Letter : g Current Letter : h
Break Statement: It brings control out of the loop.
for letter in 'shishirkantsingh': #break the loop as soon it sees 'i'or 'a' if letter == 'i' or letter == 'a': break print 'Current Letter :', letter Output: Current Letter : i
Pass Statement: 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 'shishirkantsingh': pass print 'Last Letter :', letter Output: Last Letter : h