Using a for loop: interactive
Contents
Using a for loop: interactive#
If we want to do something many times, or for many different values, we can use a for loop. The lines of code to be repeated are indicated by indenting them. Code is indented by using 4 spaces (or Tab within Jupyter notebooks). You can type Backspace to remove an indentation.
The loop ends when there’s a line with non-indented code, or when the code ends. Here is an example for loop which prints 10 numbers, then ‘Done’ when it’s finished:
for x in range(10):
print('Inside the for loop')
# You can have multiple indented lines
# You can also add as many comments as you like
print(x)
print('Done')
Inside the for loop
0
Inside the for loop
1
Inside the for loop
2
Inside the for loop
3
Inside the for loop
4
Inside the for loop
5
Inside the for loop
6
Inside the for loop
7
Inside the for loop
8
Inside the for loop
9
Done
Quick exercise#
Use the for loop to print the first 20 integers, use range(1, 21) to start from 1. Even though the range ended with \(21\) what was the last integer that was printed?
There’s several things we note here.
The
forline ends with a colon.We introduce the
rangebuiltin command. This can be used to loop over integers. If given only one value it will count the first ten numbers. If given 2 numbers (e.g.range(4,19)it will count from the first number to the second. If given 3 numbers (e.g.range(4,19,3)it will count from the first number to the second stepping forward by the third number each time. TRY THIS OUT TO MAKE THIS CLEAR!Python, when told to count ten numbers, by default will count from 0 to 9. (0 being the first number is an important concept in python, and most computing languages (but not MATLAB), we will explore this more next week).
The last line of code is not indented, so it happens once, outside the loop.
Here’s a schema of how the for loop works (when used with range):
for variable in range(start, stop):
expression
expression
...