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 three examples. Work through them in order.
For every example, study the code carefully and write down a prediction of what
it will do when it runs. Your prediction should use the key terms
sub program, call and parameter. You can type your prediction
straight into the code as a comment, on a line starting with #.
Say which lines define a sub program, which lines call one, in what order the calls happen, and whether any data is passed in.
Only once you have written your prediction should you run the code and compare the result with what you expected.
Need more help with sub programs? Click here.
Four sub programs, and a main program underneath them.
def say_hi():
print("Why hello there!")
def offer_drink():
print("Would you care for a spot of tea?")
def offer_food():
print("Biscuit?")
def say_bye():
print("Cheerio then.")
offer_drink()
say_hi()
offer_food()
Before you run it, answer two questions on paper.
How many lines of output will there be, and in what order? The four sub programs are defined in one order and called in another, so decide which of the two orders the output follows, and write the lines out in full before you run anything.
Which of the four sub programs never runs at all? Look at the call lines at the bottom, count them, and compare that count with the number of definitions. Say what you expect to happen to the one that is left over: an error, a blank line, or nothing whatsoever.
Now run it, and check both answers.
Three sub programs that each work out a number and hand it back. A sub program that returns a value like this is called a function.
def maths1():
num1 = 50
num2 = 5
return num1 + num2
def maths2():
num1 = 50
num2 = 5
return num1 - num2
def maths3():
num1 = 50
num2 = 5
return num1 * num2
output_num = maths2()
print(output_num)
Predict the single number this outputs. Work out which of the three functions is
called, what it returns, and what ends up in output_num. Then run it.
The three functions all use the same two values and differ only in one character.
Once you have checked your prediction, change the call to maths1() and then to
maths3(), and confirm that you can predict those two answers as well.
A sub program that is given something to work with.
def location(country):
print("I am from " + country)
location("Brazil")
Predict the line this outputs, and say what the word country in the brackets of
the def line is doing there. Then run it.
Change "Brazil" to a different country and run it again. The sub program
itself does not change, so work out what does.
Make sure that you check for the following things:
def line.def line.