Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/02-Python Statements/04-while Loops.ipynb
Views: 648
while Loops
The while
statement in Python is one of most general ways to perform iteration. A while
statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met.
The general format of a while loop is:
Let’s look at a few simple while
loops in action.
Notice how many times the print statements occurred and how the while
loop kept going until the True condition was met, which occurred once x==10. It's important to note that once this occurred the code stopped. Let's see how we could add an else
statement:
break, continue, pass
We can use break
, continue
, and pass
statements in our loops to add additional functionality for various cases. The three statements are defined by:
Thinking about break
and continue
statements, the general format of the while
loop looks like this:
break
and continue
statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if
statement to perform an action based on some condition.
Let's go ahead and look at some examples!
Note how we have a printed statement when x==3, and a continue being printed out as we continue through the outer while loop. Let's put in a break once x ==3 and see if the result makes sense:
Note how the other else
statement wasn't reached and continuing was never printed!
After these brief but simple examples, you should feel comfortable using while
statements in your code.
A word of caution however! It is possible to create an infinitely running loop with while
statements. For example:
A quick note: If you did run the above cell, click on the Kernel menu above to restart the kernel!