Python Data Presistence – while Statement

Python Data Presistence – while Statement

The while keyword constructs a conditional loop. Python interpreter evaluates the boolean expression and keeps on executing the subsequent
uniformly indented block of statements as long as it holds true. The moment it is no longer true, the repetition stops, and the program flow proceeds to the next statement in the script. A syntactical representation of usage of while loop is as follows:

Example

#using while statement
while expression==True:
#while block
. . .
end of while block
#rest of the statements

One way to control repetition is to keep its count and allow the next round of execution of block till the count exceeds the desired limit. In the following code snippet, the block executes repeatedly till the count is <= 5.

Example

#while-1.py
count=0
while count<5:
#count repetitions
count=count+1
print ("This is count number",count)
print ("end of 5 repetitions")

Output

E:\python 3 7>python whi1e- 1.py 
This is count number 1 
This is count number 2 
This is count number 3 
This is count number 4 
This is count number 5 
end of 5 repetitions 

E:\python37>

The expression in while statement is executed before each round of repetition (also called iteration). Here is another example to consolidate your understanding of the while loop.

The following code generates the list of numbers in the Fibonacci series. First, the two numbers in the list are 0 and 1. Each subsequent number is the sum of the previous two numbers. The while loop in the code adds the next 10 numbers. The iterations are counted with the help of variable ‘i’. the sum of numbers at i* and (Ml)* position is appended to the list till ‘i’ reaches 10.

Example

#fibolist . py
FiboList= [ ]
i = 0
max=1
FiboList.append(i)
FiboList.append(max)
while i<10:
#next number is sum of previous two
max=FiboList[i]+FiboList[i+1]
FiboList.append(max)
i = i + l
print ('Fibonacci series:1,FiboList)

Output

E : \py thon3 7 >py thon fibolist.py 
Fibonacci series: [ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89] 

E:\python37>