while loop

while is a looping statement that will iterate over a block of code until the entered test expression is true. We use this loop when we don't know how many times the iterations will go on. Refer to the following syntax:

while test_expression:
while body statements

In the while loop, first we will check the test expression. The while block will get executed only if the test expression is true. After one iteration, the expression will be checked again and this process continues until test_expression evaluates to false. This is illustrated in the following diagram: 

The following is an example of the while loop:

a = 10
sum = 0
i = 1
while i <= a:
sum = sum + i
i = i + 1
print("The sum is", sum)


Output:
The sum is 1
The sum is 3
The sum is 6
The sum is 10
The sum is 15
The sum is 21
The sum is 28
The sum is 36
The sum is 45
The sum is 55
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset