Python While Loop
while is simplest loop in python programming that is depending of expression which are provide by program. result of expression in boolean form. if that result are not false then that will executes loop statement.

There syntax as follows.
while expressionCondition:
#statements
#statements-N
For example
index=10
#expression (index<=15)
while index<=15:
#statements
print(index)
index+=1
Output
10
11
12
13
14
15
When expression is false, then terminates execution of while loop. that is a very simple example. we can used any kind of expression and condition. let take another example to print list elements using while loop.
listData=[1,2,4,5,6] #simple list
terminate=len(listData) #get size of list
index=0
while index<terminate: #expression
print(listData[index]) #display list data
index+=1 #modified index
Output
1
2
4
5
6
We can print list element using of "for" loop of very efficient manner. but that is an also alternate to display list element.
Nested while loop in python
Nested is a way to organize one conditional block inside another conditional block in similar type. in similar way to define one loop inside another (while loop) that is called nested of while loop.
while expression1:
#statements
while expression2:
#statements
while expressionN:
#statements
For example
#Nested while loop example
listData=[100,[1,2,3],[9,7,8,11]]
i=0
j=0
innerLength=0
outerLength=len(listData)
#outer while loop
while i<outerLength:
j=0
if(type(listData[i])==list) :
innerLength=len(listData[i])
else:
print("list[",i,"]",listData[i]) #not list
innerLength=0
#inner while loop
while j<innerLength:
print("list[",i,"][",j,"]",listData[i][j])
j+=1
i+=1
Output
list[ 0 ] 100
list[ 1 ][ 0 ] 1
list[ 1 ][ 1 ] 2
list[ 1 ][ 2 ] 3
list[ 2 ][ 0 ] 9
list[ 2 ][ 1 ] 7
list[ 2 ][ 2 ] 8
list[ 2 ][ 3 ] 11
in similar way we can use any number of nested while loops in programs.
Break statement
Brake are used to terminate loop execution within the specified condition.
point=10
while True:
if(point<=-1 or point>=20):
break #condition to terminate loop
print(point)
point+=3
print("After terminate loop :",point)
Output
10
13
16
19
After terminate loop : 22
continue statement
This statement are manage execution flow of loop. this statement are only used within the loop.
point=1
while point<10:
point+=1
if(point>=3 and point<=7):
continue
print(point)
print("After terminate loop :",point)
Output
2
8
9
10
After terminate loop : 10
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment