< Prev  |  Home  |  Next >

Arrays and Loops

Python allows you to easily iterate (loop) through an array. For example, to print each character in a string, we can simply type:

This works the same for items in a list:

If it’s ok, I’d like to show you another way of iterating through an array. The way I’m going to show you is harder than the easy way above, but it’s a helpful way of better understanding arrays. Remember that you can access an item of an array by using it’s index. So, in a list of homework marks:

homeworkMarks[0] is 10, and homeworkMarks[5] is 2. Another way to iterate through the marks is to use a variable for the index and use a ‘while’ loop:

In the code above, firstly homeworkMarks[0] is printed, as the value of ‘pos’ is 0. Then 1 is added to ‘pos’, so the next time around pos[1] is printed. And so on, as long as ‘pos’ isn’t over 7.

We could also easily write another program to reset the homework marks. All we need to do is loop through the list of marks, and set the mark to 0:

There are two things we could do to improve this program. Firstly, we could future-proof it by resetting the marks to 0 while the position value is less than the length of the list. That way, if we ever change the length of the list, the program will still work:

We could also add a line to test the program, so that we know that the resetting has worked. Here’s the complete program:

Challenge

Code and test a program to calculate the total and average (mean) of a set of homework marks using a ‘while’ loop.

< Prev  |  Home  |  Next >