Python/While Statement

< Python

Objective

  • Learn about Python's loop statement, while.
  • Learn about three dependent statements, else, break, and continue.

Lesson

The While Statement

Although the if statement from the previous lesson can serve many purposes, it isn't good at being recursive. This means that the said statement cannot loop over and over again. This is where the while statement comes into play. This statement will execute its code block over and over again until its conditions are false. This can be useful if something needs to be repeat over and over for a said amount of time. Some examples are given below.

>>> pop = 0
>>> while pop != 5:
...     pop += 1
...     print(pop)
...
1
2
3
4
5
>>> eggs = [12, 4, 2, 6, 11, 23]
>>> while eggs:
...     print(eggs[0])
...     del eggs[0]
...
12
4
2
6
11
23
>>> while False:
...     print("This will never print!")
...
>>> spam = 10
>>> while spam:
...     spam -= 1
...     print(spam)
...
9
8
7
6
5
4
3
2
1
0


while statements condition is always true or false, like the if statement. This means Booleans math can be used to persuade the looping. So since while False: will never execute, what would while True: do? You'd be correct if you said it would infinitely loop. Since this will be important later on, we'll spend more time on it later on in the lesson.

The Else Statement

Unlike a lot of other computer languages, Python allows you to use a else statement in conjunction with a while statement. When a while statement finishes its loop naturally, it will then execute the else statement. If the while statement stops prematurely for any reason, it will not execute the else statement. An example is given below.

>>> spam = 0
>>> while spam != 10:
...     spam += 1
...     print(spam)
... else:
...     print("Done printing spam!")
...
1
2
3
4
5
6
7
8
9
10
Done printing spam!
>>> while True:
...     pass
... else:
...     print("I'll never get seen on the screen!")
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt


In the second example, ctrl+c is used to generate a KeyboardInterrupt. Like it was stated a paragraph above, since the while statement ended prematurely the else statement was never executed.

The Break Statement

There can be times when you want to prematurely end a while statement. The break statement can be used to accomplish this. The break statement can be used to prematurely end the while statement that it's nested in. This means it will end only one while statement, not all of them. An example is given below.

>>> pop = 0
>>> while True:
...     print(pop)
...     pop += 1
...     if pop == 10:
...         break
...
0
1
2
3
4
5
6
7
8
9


The above example demonstrates that a while loop can be ended, even if it is True. You should also note from the example that the break statement doesn't require a colon (:), which means new indentation isn't needed. Putting a colon at the end of break will cause an error; the omission of the colon isn't optional, it's mandatory.

Continue Statement

Although the break statement comes in handy, the continue statement is just as useful. Unlike the break statement, the continue statement will stop the current execution of code and go back to the beginning of the while statement. This can be used to skip part of the code and not end the loop at the same time. The continue statement is used just like the break statement. An example is given below.

>>> bacon = 0
>>> while bacon != 10:
...     bacon += 1
...     if bacon < 5:
...         continue
...     print(bacon)
...
5
6
7
8
9
10


Although the example could have easily omitted the continue, it demonstrates how it works. The continue statement is to used to reduce the amount of indenting and nesting used; it would be easier to check five conditions and use a continue if they fail, then to nest five if statements. This can reduce the amount of typing needed and, as a result, will increase readability and code clarity.

Assignments

  • Work with the while statement and get a general feeling of how it works.
  • PEP 315 proposed that an optional do clause should be added to the while statement, although it was ultimately rejected. Read PEP 315. Why do you thing it was rejected? How would this effect readability?

Completion status: Ready for testing by learners and teachers. Please begin!

This article is issued from Wikiversity - version of the Thursday, April 02, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.