Software tutorial/Loops
Looping with a for loop is easy when you know how many iterations will be required.
MATLAB | Python |
---|---|
The simplest loop can be written: for k = 0:4
disp(k)
end
and the output should be: 0
1
2
3
4
The reason why this works is that instruction k = 0:4 creates a vector, starting at 0 and ending at 4, in steps of 1.0. You can verify this in MATLAB: >> k = 0:4
k =
0 1 2 3 4
Try looping and printing with these vectors. What is the output you expect when:
If you need help in MATLAB, you can type, for example: help colon
and it will show you how to use the colon operator. |
The simplest loop can be written: for k in range(5):
print(k)
and the output should be: 0
1
2
3
4
Why does the output not include the number 5? In Python, you can always check what a function does by using the help command. For example: >>> help(range)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
This shows you that the only input required to the range() function is the stop input - the other inputs, [start] and [step] have square brackets in the HELP text, indicating that they are optional inputs. Using the above HELP text, what would you expect in Python if you typed:
|