"while" Statement for Execution Loop

This section provides a quick introduction of 'while' statement, which executes a block of sub-statements repeatedly while the given condition is valid.

What Is "while" Statement? A "while" statement is a compound statement that executes a block of sub-statements repeatedly while the given condition is valid.

A "while" statements must have a "while" clause followed by an optional "else" clause:

```while condition:
sub-statement
sub-statement
...
else:
sub-statement
sub-statement
...
```

Two special statements can be used the sub-statement block:

• "break" statement can be used to break the "while" statement and terminate its execution.
• "continue" statement can be used to skip the remainder of the sub-statement block and jump back to the "while" clause header.

Here is a Python sample code, while_test.py, that shows you how to use "while" statements.

```#  while_test.py
#

upperLimit = 20
i = 3
while i<upperLimit:
isPrime = True
j = 2
while j<=i//2:
isPrime = i%j > 0
if not isPrime:
break
j = j + 1

if isPrime:
print("   "+str(i)+" is a prime number.")
i = i + 1

print("Reached the upper limit "+str(upperLimit))
```

If you run this sample code, you should get:

```herong> python while_test.py
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.
Reached the upper limit 20
```

Notice that we have a "while" statement nested inside another "while" statement. The "break" statement inside the inner "while" statement only breaks the immediate containing "while" statement, not the outer "while" statement.