while <expression>: Body of while
>>> a=10 >>> while a>0: print ("Value of a is",a) a=a-2 Value of a is 10 Value of a is 8 Value of a is 6 Value of a is 4 Value of a is 2 >>>
Firstly, the value in the variable is initialized.
Secondly, the condition/expression in the while is evaluated. Consequently if condition is true, the control enters in the body and executes all the statements . If the condition/expression passed results in false then the control exists the body and straight away control goes to next instruction after body of while.
Thirdly, in case condition was true having completed all the statements, the variable is incremented or decremented. Having changed the value of variable step second is followed. This process continues till the expression/condition becomes false.
Finally Rest of code after body is executed.
>>> n = 10 >>> sum = 0 >>> i = 1 >>> while i <= n: sum = sum + i i = i+1 # update counter # print the sum print("The sum is", sum) 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 >>>
Same as that of for loop, we can have an optional
else block with while loop as well.
else part is executed if the condition in the while loop evaluates to
False. The while loop can be terminated with a break statement.
In such case, the
else part is ignored. Hence, a while loop's
else part runs if no break occurs and the condition is false.
>>> # Example to illustrate >>> # the use of else statement >>> # with the while loop >>> counter = 0 >>> while counter < 3: print("Inside loop") counter = counter + 1 else: print("Inside else") Inside loop Inside loop Inside loop Inside else >>>