difference is huge in that it means you can specify a loop
that could conceivably go on forever, as long as the loop
condition is still true. You can use else with a while
loop. An else statement after a while loop executes
when the condition for the while loop to continue is no
longer met. Example 3-3 shows a count and an else
statement.
Example 3-3 else Statement with a while Loop
Click here to view code image
>>> count = 1
>>> while (count < 5):
... print("Loop count is:", count)
... count = count + 1
... else:
... print("loop is finished")
...
Loop count is: 1
Loop count is: 2
Loop count is: 3
Loop count is: 4
loop is finished
You can probably see similarities between the loop in
Example 3-3 and a for loop. The difference is that the
for loop was built to count, whereas this example uses
an external variable to determine how many times the
loop iterates. In order to build some logic into the while
loop, you can use the break statement to exit the loop.
Example 3-4 shows a break with if statements in an
infinite while loop.
Example 3-4 Using the break Statement to Exit a
Loop
Click here to view code image
while True:
string = input('Enter some text to print.
\nType "done" to quit> ')
if string == 'done' :
break
print(string)