3. Control Flow: Loops
While Loops
The #\color{#8959A8} {\mathtt{\text{while}}}# loop is the other syntactic structure that supports repeated execution. The #\color{#8959A8} {\mathtt{\text{while}}}# loop differs from the #\color{#8959A8} {\mathtt{\text{for}}}# loop in what drives the repetition, for #\color{#8959A8} {\mathtt{\text{for}}}# loops it's iterables, while for #\color{#8959A8} {\mathtt{\text{while}}}# loops it's expressions. A #\color{#8959A8} {\mathtt{\text{while}}}# loop will continue looping while its corresponding expression remains true, when the expression evaluates to false the loop is stopped.
\begin{split}
\color{#8959A8} {\mathtt{whil}} & \color{#8959A8}{\mathtt{e}} \textit{ expression} \mathtt{:}\\
& \textit{statement}
\end{split}
Here, expression is any valid Python expression that can be evaluated in boolean context, in other words, expressions that can be interpreted as either #\color{#F5871F}{\mathtt{\text{True}}}# or #\color{#F5871F}{\mathtt{\text{False}}}#. The indented statement refers to the body of the loop, the code that will be executed every iteration.
For example, here we see a simple #\color{#8959A8} {\mathtt{\text{while}}}# loop that counts to #\color{#F5871F}{\mathtt{\text{10}}}#. Naturally, values within the expression are also changed within the loop, if this wasn't the case the loop would run infinitely. |
|
You have probably noticed that #\mathtt{\text{var} \color{#3e999f}{\text{ = }} \text{var} \color{#3e999f}{\text{ + }}\color{
#F5871F}{\text{1}}}# is a very common variable assignment pattern that occurs in loops. It is in fact so common that this particular syntax received its own shorthand notation.
Shorthand | Expression |
#\mathtt{\text{x} \color{#3e999f}{\text{ += }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ + }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ -= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ - }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ *= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ * }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ /= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ / }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ **= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ ** }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ %= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ % }} \text{y}}# |
#\mathtt{\text{x} \color{#3e999f}{\text{ //= }} \text{y}}# | #\mathtt{\text{x} \color{#3e999f}{\text{ = }}\text{x} \color{#3e999f}{\text{ // }} \text{y}}# |
The shorthand notation is supported by all arithmetic operators in Python.
>>> var = 0
>>> var += 1 >>> print(var) |
1
|
Or visit omptest.org if jou are taking an OMPT exam.