Loops in Python
Sometimes we may require to repeat a set of statements multiple times
continuously, in these situation the Language provides Loop Statement for the
same.
Python programming language provides three ways for executing the
loops.
While Loop:
In Python , while loop is used to execute a block of statements repeatedly
until the given condition is satisfied.
Syntax:
while expression:
statement(s)
Example:
#Program
count=0
while(count<3):
count=count+1
print("Hi Student")
Output
Hi Student
Hi Student
Hi Student
Here, the variable count is incremented every time we enter the loop
and so if the count reaches the value 3, the loop terminates and proceeds to
the next.
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.
It is similar to that of if … else statement except that both blocks
will be executed under normal conditions.
Syntax:
while condition:
#executes these
statements
else:
#executes these
statements
Example
#Python program to illustrate combining else with value
count=0
while(count<3):
count=count+1
print("Hi Student")
else:
print("Bye")
Output
Hi Student
Hi Student
Hi Student
Bye
While the loop is repeated 3 times the else block is executed only once
at the last.
Single statement while block:
Just like the short hand if statement, if the while block has only a
single statement then we can declare the entire loop in a single line as shown
below:
#Python program to illustrate Single statement while
block
Infinite loop
count=0
while(count==0):print("Hi
Student")
Note: It is suggested not to use this type of loops as it is a never
ending infinite loop where the condition is always true and you have to
forcefully terminate the program execution.
for in loop:
For loops are used for sequential traversal. For example : traversing a
list or string or array etc. In Python , there is no C language style for loop,
i.e., for(i=0;i<n;i++). There is ‘for in’ loop which is similar to for each
loop in other languages. Let us learn how to use for in loop for sequential
traversals.
syntax:
for iterator_val in sequence:
statements(s)
It can be used to iterate over a range and also iterators.
Example1:
#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
Example 2:
#Python program to illustrate Iterating over a
list,tuple,string,dictionary and set
#List
Iteration
print("List Iteration")
l=["hi","hello","welcome"]
for i in l:
print(i)
#Iterating
over a tuple(immutable)
print("\nTuple
Iteration")
t=("welcome","to","the","world")
for i in t:
print(i)
#Iterating
over a String
print("\n
String Iteration")
s="Hello
World"
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]))
#Iterating
over a set
print("\n
Set Iteration")
set1={1,2,3,4}
for i in set1:
print(i)
Output
List Iteration
hi
hello
welcome
Tuple Iteration
welcome
to
the
world
String Iteration
H
e
l
l
o
W
o
r
l
d
Dictionary Iteration
xyz 123
abc 345
Set Iteration
1
2
3
4
Iterating by the 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 then iterate over the
sequence within the range of this length.
Example
list=["hi","hello","apple"]
for index in
range(len(list)):
print(list[index])
Output
hi
hello
apple
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.
Below example explains how to do this
#Python program to
illustrate combining else with for
list=["hi","hello","apple"]
for index in
range(len(list)):
print(list[index])
else:
print("Now inside else Block")
Output
hi
hello
apple
Now inside else Block
Nested Loops:
Python programming language allows to use one loop inside another loop.
That means there can be a for statement inside a while statement or vice versa
or For within For and While within While. Following section shows few examples
to illustrate the concept.
Syntax:
for iterator_var in sequence:
for
iterator_var in sequence:
statements(s)
The syntax for a nested while loop statement in the python programming
language is as follows:
while expression:
while
expression:
statement(s)
#Python program to illustrate nested for loops in Python
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
for i in
range(1,5):
for j in range(i):
print(j+1,end=' ')
print()
Output
1
1 2
1 2 3
1 2 3 4
Loop Control Statements:
Loop Control statements change execution from their 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, from the point
from where it is executed thus skipping the statements below it in the Loop.
Example
#Prints all letters except ‘C’ and ‘ ‘
for letter in
'Hello World':
if letter=='o' or letter==' ':
continue
print('Current Letter:',letter)
var=10
Output
Current Letter: H
Current Letter: e
Current Letter: l
Current Letter: l
Current Letter: W
Current Letter: r
Current Letter: l
Current Letter: d
Break Statement:
Unlike Continue , this statement will shift the control to outside the
Loop and terminates it.
Example
for letter in
'Hello World':
#break the loop as soon it sees 'o' or 'e'
if letter=='o' or letter==' ':
break
print('Current Letter:',letter)
Output
Current Letter: H
Current Letter: e
Current Letter: l
Current Letter: l
Pass Statement:
This is useful when we want to test
run a set of statements before finishing it completely.
Example
#An empty loop
for letter in
'Hello World':
pass
print('Last
Letter:',letter)
Output
Last Letter: d
No comments:
Post a Comment