The 'while' statement:
In the previous tutorials I used two programs nLines and countdown, that use recursion to perform repetition, which
is also called iteration. Because iteration is so common, Python provides several features to make it easier. One of
them is the 'while' statement. Here's the countdown function transformed with a while statement:
def countdown( n ):
while n > 0:
print n
n = n - 1 #This can be rewritten as n -= 1
print "Blastoff!"
In English this means: "While n is greater than 0, continue displaying the value of n and then reducing the value of
n by 1. When you get to 0, display the word "Blastoff!"
Here's the flow of execution of a while loop:
1.Evaluate the condition, yielding True or False.
2.If the condition is False, exit the while statement and continue the execution at the next statement.
3.If the condition is True, execute each of the statements in the body and then go back to step 1.
The body of the loop should change the value of one or more variables so that eventually the condition becomes False
and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop.
e.g.1 Print all numbers from 0 to n:
n = input( "Enter last number >> " )
number = 0
while number <= n:
print number
number = number + 1
e.g.2
n = 0
while n < 100:
if n % 10 == 0 and n != 0:
print
if n < 10:
print str( n ) + " ",
else:
print n,
n = n + 1
Output:
>>>
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
50 51 52 53 54 55 56 57 58 59
60 61 62 63 64 65 66 67 68 69
70 71 72 73 74 75 76 77 78 79
80 81 82 83 84 85 86 87 88 89
90 91 92 93 94 95 96 97 98 99
>>>
Author: Georgi Christov ( aka masterofpuppets )
e-mail: programming.unlimited@abv.bg