Functions
When you call a subprogram, you write its name followed by brackets. Inside the brackets you put the arguments — the actual values you are handing over for this particular call. A subprogram written with two parameters needs two arguments, and the first argument is matched to the first parameter, the second to the second. Swap them round and a function meant to work out price - discount would take the discount off the wrong number.
How you call depends on whether the subprogram is a procedure or a function.
A function hands a value back to the point where it was called, so the call itself counts as a value. That means you can store it in a variable, or drop it straight into an expression or a print():
score = bonus(40, 3) — the returned value is stored in score.total = bonus(40, 3) + bonus(10, 1) — two calls, each used as part of the arithmetic.print(bonus(25, 4)) — the value is passed straight to print().Because a call produces a value, a function can be used wherever a value is expected. The brackets are essential: writing bonus on its own refers to the function without running it, while bonus(40, 3) runs it and gives you the value.
A procedure does a job but sends nothing back, so its call goes on a line as a statement by itself: show_medal('Gold', 3). There is no value to store or to add to a number, so a procedure call cannot be part of an expression. A procedure that uses print() has only displayed text on the screen — that text is not returned to whoever made the call.
def print_score(level, correct):
points = level * correct
print("Level " + str(level) + " scored " + str(points))
def earned_points(level, correct):
return level * correct
print_score(3, 12)
best = earned_points(3, 12)
print(best)
print(earned_points(2, 5) * 10)Output:
Level 3 scored 36
36
100
The call print_score(3, 12) is a statement, while earned_points(3, 12) is used inside a print() because it is a value.
Edexcel GCSE Computer Science · Functions