Back

Nested for loops and dry-running code

Q1. Type this code in and get it working:

1  for x in range (1, 4):
2      for y in range (1, 4):
3          print(x,"*",y,"=",x*y)

Q2. Can you describe what this does?
Q3. This type of construction, where you put e.g. a for loop inside another for loop is known as a 'nested' loop. They are very powerful because they can achieve a lot with just a few lines of code, although to start with they can be difficult to visualise. To help us visualise complex code, we can use a technique called 'dry-running' the code. We create a table and then we step through the code as if we were the computer. This is also a great way of tracking down errors in code that we just can't seem to spot by any other method!

We need a column for the line numbers, a column for any variable that might change, and a column for the output. Every time a variable changes (in this case, whenever either x or y changes), we move on to the next line. If there is an output (from a print statement, for example), then we fill in the output column and again, move on to the next line. We only put in a new value for a variable when it changes. Print out this table and complete it. It has been started for you.

dryrun1

 Q4. You are going to dry-run a program. Create a table for this code:

1  for x in range (2, 4):
2      for y in range (1, 4):
3          print(x, end=" ")
4          temp = (y * y) + x
5          print (temp)

Remember. you need a column for the line numbers, a column for each variable that might change and a column for the output. When you have created your table, complete it by dry-running your code.
Q5. Compare your table to a neighbour's table. Were they the same or different, and if they were different, why?
Q6. Enter the code into Python and get it working. Is the output from the working program the same as you predicted from dry-running your code?
Q7. Create your own nested for loop and then pass it to a neighbour. Your neighbour must firstly dry-run it, secondly get it working in Python and finally, compare their output from dry running the code to actually running it.

Back