Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions
Privacy Policy




Iterative Processing: The while Statement

The while statement looks like this:

while expression : suite

The suite is an indented block of statements. Any statement is allowed in the block, including indented while statements.

As long as the expression is true, the suite is executed. This allows us to construct a suite that steps through all of the necessary tasks to reach a terminating condition. It is important to note that the suite of statements must include a change to at least one of the variables in the while expression . When it is possible to execute the suite of statements without changing any of the variables in the while expression , the loop will not terminate.

Let's look at some examples.

t, s = 1, 1
while t != 9:
    t, s = t + 2, s + t

The loop is initialized with t and s each set to 1. We specify that the loop continues “while t ≠ 9”. In the body of the loop, we increment t by 2, so that it will be an odd value; we increment s by t, summing a sequence of odd values.

When this loop is done, t is 9, and s is the sum of odd numbers less than 9: 1+3+5+7. Also note that the while condition depends on t, so changing t is absolutely critical in the body of the loop.

Here's a more complex example. This sums 100 dice rolls to compute an average.

s, r = 0, 0
while r != 100:
    s,r = s + d1+d2, r + 1
print s/r

We initialize the loop with s and r both set to zero. The while statement specifies that during the loop r will not be 100; when the loop is done, r will be 100. The body of the loop sets d1 and d2 to random numbers; it increments s by the sum of those dice, and it increments r by 1. When the loop is over, s will be the sum of 100 rolls of two dice. When we print, s/r we print the average rolled on two dice. The loop condition depends on r, so each trip through the loop must update r.

  Published under the terms of the Open Publication License Design by Interspire