Loops#
Python offers us two ways to loop over data: for
and while
.
Each method is basically check that some condition is True
, and if it is, it executes the body of code inside the loop. The same is also true not just for expressions evaluating to True
, but also when some list of values is consumed and exhausted.
Here's an example of a loop that's continuing to loop because some expression is True
, stopping when that's no nothing the case:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
We set n
to equal 10
, and then we use a while
loop to say: whilst the value inside of n
is greater than the number 0
(which is True
straight away), execute our code. Inside of our code, we change the value of n
, reducing it by 1
each time until it eventually 0
, which means the while
loop's expression will equal False
, and the loop will break.
Here's an example of a for
loop based on an enumerator:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
The range()
function returns a list of numbers starting with 1
and going to 10 - 1
, or 9
. The for
loop then iterates over the list of numbers, storing the value inside of n
, which is then used inside the body of the loop.
We can also do something else inside of a loop: skip a loop using continue
or break
out of the loop entirely. Here's an example (of course):
1 2 3 4 5 6 7 8 9 |
|
If we put this inside of a file called "for-loops.py" and run it:
1 2 3 4 5 6 7 8 9 |
|
We can see it loops fine, skipping 5
and breaking out of the loop just before 10
is printed (sorry.) This can be handy when you want to ignore values inside of some set that don't interest you, or you want to exit the loop because some external condition has been satisfied.