In a predict and run task you do not write code from scratch. You start from a small piece of working code, work out what you think it will do before you run it, and then run it to check whether you were right.
This task contains eight examples. They are short on purpose, and they are in order, so work through them one at a time.
For every example, study the code carefully and write down a prediction before
you touch the Run button. Your prediction should use the key terms iteration
and counter, and it should say two things: which lines are inside the loop,
and how many times those lines run. Where the counter’s value ends up in the
output, predict the exact numbers. You can type your prediction straight into
the code as a comment, on a line starting with #.
Only once you have written your prediction should you run the code and compare the result with what you expected.
Need more help with for loops?
Click here.
for counter in range(10):
print(counter)
print("Finished")
How many lines of output are there, what is the first one, and what is the last
number printed before Finished?
print("This program uses iteration")
for counter in range(10):
print("Hello")
print("Finished")
The counter is never printed here. Predict how many times Hello appears, and
how many times the first and last lines run.
for count in range(3):
print("Hello")
print("There")
print("You")
Two of these three prints repeat and one does not. Predict the whole output, line by line, and say what decides which prints belong to the loop.
message = "This is how you get code to repeat."
for counter in range(1, 10):
print(message)
Count carefully. The range starts at 1 and stops at 10, so predict exactly how many lines this prints, and check your answer against the output.
for counter in range(1, 5):
print(counter)
Predict every number this prints. Then change the 5 to a 6, predict again, and run it to see whether the loop gained one repetition or lost one.
for counter in range(5, 25, 2):
print(counter)
This range has a third number. Predict the first value, the last value and how many lines there are in total.
num = 4
for counter in range(1, num):
print(counter)
The stop value is a variable this time. Predict the output, then change num to
7 and predict how the output changes before you run it again.
number = 2
for count in range(1, 11):
print(count * number)
The body does a calculation with the counter. Predict all of the output, and say what this program would be called if you met it in a maths lesson.
Make sure that you check for the following things:
for.range(...) to work
through.for line has a colon (:) at the end.for, and all of it
by the same amount. Never mix tabs and spaces in one file.range(...) are separated by commas.