ICS3U Computer Science • Ontario Grade 11

Revision sheet: functions, parameters and scope (ICS3U)

This sheet is not a summary of the subprograms chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks when they write, call and trace functions, and which precise gesture avoids each loss.

Most of these mistakes give no error message, or give it far from their cause: a function that displays its result instead of giving it back, two arguments in the wrong order, a list changed behind the caller's back. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 8 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

A function talks to its caller through two doors only, the arguments copied into the parameters in the order of the call and the value sent back by return; every other name it creates is local and disappears when the call ends.

Topics covered

  • Subprogram
  • Function definition and call
  • Parameters and arguments
  • Positional arguments
  • Return value
  • None value
  • Local variable
  • Global variable
  • Variable scope
  • Call stack
  • Array passed as a parameter
  • Modularity and structure chart

The essentials

What happens at a call

  • • A def statement only defines the function: nothing in its body runs until a call.
  • • At the call, each argument is evaluated, then copied into the parameter at the same position: in rides_left(2000, 335), balance receives 2000 and fare receives 335.
  • • The call gets a frame of its own, where its parameters and the names it assigns live; the frame is erased when the call ends.
  • • return sends one value back and ends the call at once: the call, in the caller's line, is replaced by that value.
  • • A call that reaches the end of the body without return gives back None.
  • • A call written inside another call runs first: its value is an argument of the outer call.
n = rides_left(2000, 335)Frame of rides_leftbalance = 2000fare = 335rides = 5arguments copied in orderreturn 5n = 5the frame is erased when the call ends
The two arguments are copied, in order, into balance and fare; the call gives back 5, stored in n, and the frame with balance, fare and rides disappears.

On a trace, write each call as a small frame, parameter = argument in the order of the header, and cross the frame out at the return.

Where a name exists

  • • A parameter, and every name assigned in the body, is local: it exists during the call only, and the main program cannot use it.
  • • A function may read a global name that it does not assign: its value is looked up outside.
  • • A name assigned anywhere in a function is local in the whole function: reading it before its assignment raises an UnboundLocalError, even if a global name has the same spelling.
  • • global name, at the top of the body, lets the function assign a global variable. The usual design passes the value in and returns the new one.
  • • A number parameter receives a copy of the value: n = n + 1 inside the function leaves the caller's variable unchanged.
  • • An array parameter refers to the caller's array: t[i] = ... changes it for the caller, t = [...] only gives the local name another array.

Two variables with the same name, one global and one local, are two different variables: a trace keeps them in two different frames.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

How a function and its caller exchange values

What the function does, and what the caller gets back. Every example was run in Python 3.

In the functionWhat reaches the callerResult for the caller
return value the value, in place of the call a value to store or use

Example: box_volume(20, 15, 10) is worth 3000; v = box_volume(20, 15, 10) keeps it.

n = n + 1 on a number parameter nothing the caller's variable unchanged

Example: x = 4, then add_one(x) with n = n + 1 in its body: x still holds 4.

t[i] = ... on an array parameter the change of the cells the caller's array changed

Example: scores = [12, 9, 15], then add_bonus(scores) adds 5 to each cell: scores holds [17, 14, 20].

t = [...] on an array parameter nothing the caller's array unchanged

Example: t = [0, 0, 0] in the body leaves scores as it was; the new array is lost at the return.

reading a global name nothing allowed, nothing changes

Example: With bonus = 5 outside, return p + bonus gives 17 for p = 12.

print(value), no return text on the screen None no value given back

Example: def area(w, h): print(w * h) displays 12 for area(3, 4), and area(3, 4) + 2 stops with a TypeError.

What to do: Write return w * h in the function, and print at the call if a display is wanted: print(area(3, 4)).

level = level + 1 on a global name an UnboundLocalError the program stops run-time error

Example: level = 1 outside, then level_up() with level = level + 1 in its body: the call stops before any change.

What to do: Pass the value and give the new one back: def level_up(level): return level + 1, then level = level_up(level).

Before writing a function, decide which door each value takes: a parameter to come in, return to go out. A global name read in secret is a door the caller cannot see.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. Giving a result back

the whole question, since every line that uses the result fails or receives None

What not to write

“def area(w, h): print(w * h), then total = area(3, 4) + 2 gives 14.”

What to write

“area displays 12 and gives back None, and None + 2 is a TypeError. With return w * h, total = area(3, 4) + 2 gives 14.”

Why: print sends text to the screen, not to the program; return is what makes the call worth a value at the place of the call.

2. Using a variable of the function after the call

1 to 2 marks, and a program that stops on the line that prints

What not to write

“def average(a, b): m = (a + b) / 2, then average(70, 90) and print(m) prints 80.0.”

What to write

“m exists during the call only: print(m) is a NameError. Write return m in the function, then m = average(70, 90): print(m) prints 80.0.”

Why: The frame of a call, with all its local names, is erased at the return; the returned value survives, and it is lost unless the caller stores it or uses it at once.

3. Changing a global variable in a function

the program stops at the first call

What not to write

“level = 1, and def level_up(): level = level + 1 raises the level of the game.”

What to write

“The assignment makes level local in level_up, and the call stops with an UnboundLocalError. Write def level_up(level): return level + 1, then level = level_up(level).”

Global nameslevel = 1Frame of level_up()level: no value yetlevel = level + 1 makes level local: the right side reads the local name, still empty
The global level holds 1, but in the frame of level_up the name level is local and still has no value: reading it stops the program.

Why: Python decides once for the whole function that an assigned name is local; the right side then reads a local name that has no value yet.

4. The order of the arguments

1 to 2 marks, and a wrong value that nothing flags

What not to write

“rides_left(335, 2000) gives the rides left on a card of 2000 cents, at 335 cents a ride.”

What to write

“The header is rides_left(balance, fare): write rides_left(2000, 335), which gives 5. rides_left(335, 2000) gives 0, with no error.”

Why: Arguments without names are matched to parameters by position; two numbers in the wrong order are accepted as long as the formula can compute with them.

5. An array passed to a function

1 to 2 marks on an output to predict, and data lost for the rest of the program

What not to write

“add_bonus(scores) works on a copy: scores keeps [12, 9, 15] after the call.”

What to write

“t in add_bonus refers to the array scores: t[i] = t[i] + 5 changes scores into [17, 14, 20]. To keep the original, pass a copy: add_bonus(scores[:]).”

171420scorestmain programin add_bonuswas [12, 9, 15]
scores in the main program and t in add_bonus lead to the same three cells: the bonus written through t is read through scores.

Why: An array parameter receives the caller's array itself, not a copy of its cells; an assignment to a cell is seen through every name of that array.

6. Changing a number parameter

1 mark on a trace, and a counter that never moves

What not to write

“def add_one(n): n = n + 1, then x = 4 and add_one(x): x holds 5.”

What to write

“n receives a copy of 4, and n = n + 1 changes the copy: x still holds 4. Write return n + 1 in the function, then x = add_one(x).”

Why: A number parameter is a local name that receives the value of the argument; changing it reaches nothing outside the call.

7. A result of a call left on its own line

a NameError if v was never assigned, or an old value printed if it was

What not to write

“box_volume(20, 15, 10) on its own line, then print(v), prints 3000.”

What to write

“The 3000 comes back to a line that does not keep it. Write v = box_volume(20, 15, 10), then print(v).”

Why: return gives the value to the place of the call; only an assignment, or an expression around the call, keeps it.

8. A return inside a loop

1 to 2 marks, and a function right only when the first value decides

What not to write

“def has_even(t): for x in t: if x % 2 == 0: return True, else: return False. has_even([3, 8]) gives True.”

What to write

“The else returns False after the first value, 3: has_even([3, 8]) gives False. Write return False after the loop, once every value has been tried.”

Why: return ends the call: an answer that needs the whole array can only be given after the loop.

Which method to choose

return or print, parameter or global?

Read what the statement asks of the function, and choose the door for each value.

  • If the function « gives back », « returns » or « computes » a value used later → return the value; the caller stores it or prints it

    Example: v = box_volume(20, 15, 10)

  • If the function only « displays » a message, and nothing is used later → print in the function; no return is needed

    Example: def welcome(name): print('Hello', name)

  • If the function needs a value from outside → a parameter, in the order of the header, not a global name read in secret

    Example: rides_left(balance, fare)

  • If the function must change a number the caller keeps → return the new value and assign it at the call

    Example: level = level_up(level)

  • If the function must change an array the caller keeps → change its cells, t[i] = ..., and say so in the comment under the header

    Example: add_bonus(scores) changes scores

When the same formula is needed in several places, it becomes one function called from each place: one formula, one place to correct.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Writing a function on a unit test

When to use it: « Write a function that ... and gives back ... »

  1. 1 Write the header with the name and the parameters in the order of the statement.
  2. 2 Under the header, a comment that says what the function gives back, and the units of the parameters.
  3. 3 Write the body with the parameters and local names only, no global name read in secret.
  4. 4 Check that every path ends with a return, and that an answer that needs the whole loop is given after the loop.
  5. 5 Work out two calls by hand, a usual one and a boundary one, and write them with their expected values.

Concluding sentence

“rides_left(2000, 335) should give 5, since 5 × 335 = 1675 is at most 2000 and 6 × 335 = 2010 is more.”

The trap: Writing print in place of return, so that the function displays the right number and gives back None.

Marking: A common split: 1 mark for the header, 2 for the body and its return, 1 for the calls worked out by hand.

Tracing a program that calls functions

When to use it: « What does this program print? » with one or several def

  1. 1 Skip the def statements: they define, they do not run.
  2. 2 At each call, write a frame with parameter = argument, in the order of the header.
  3. 3 Follow the body until the first return reached, then replace the call by the value returned.
  4. 4 Cross the frame out: its local names no longer exist.
  5. 5 Write the printed lines in the order the print statements run, inner calls first.

Concluding sentence

“box_volume(20, 15, 10): length = 20, width = 15, height = 10; the call returns 3000, which v receives.”

The trap: Using a local name of a crossed-out frame later in the trace.

Marking: A common split: 1 mark per frame correctly filled, 1 for the output in order.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • Every path ends with return

    Follow each branch of each if to the end of the function: does it reach a return?

    def result(p): if p >= 50: return 'pass' gives back None for 40: add return 'fail' after the if.

  • The order of the arguments

    Read the header next to each call, parameter by parameter.

    rides_left(balance, fare): the call is rides_left(2000, 335). rides_left(335, 2000) gives 0.

  • Every result kept

    Each call of a function that returns a value sits after an =, inside print(), or inside an expression.

    box_volume(20, 15, 10) alone loses the 3000: write v = box_volume(20, 15, 10).

  • No local name outside its function

    List the names used by the main program: none of them may be a parameter or a local name of a function.

    print(rides) after rides_left(2000, 335) is a NameError: rides was local.

The typical problem, taken apart

A transit card: writing and testing rides_left()

A transit card holds a balance in cents, and each ride costs a fare in cents. Write a function rides_left(balance, fare) that gives back how many full rides the balance still pays for.

Test it with chosen calls, then give rides_left(2000, 335).

Python
def rides_left(balance, fare):
    # number of full rides the balance pays for, amounts in cents
    rides = balance // fare
    return rides
print(rides_left(2000, 335))

Step 1

Header: def rides_left(balance, fare):, the parameters in the order of the statement, then a comment that says what is given back and the unit of the amounts.

Why

The header is what the caller reads: the order of its parameters is the order of every call.

Step 2

Body: rides = balance // fare, then return rides. For 2000 and 335: 5 × 335 = 1675 is at most 2000 and 6 × 335 = 2010 is more, so 2000 // 335 = 5.

Why

// keeps the whole number of rides. Amounts in cents stay whole numbers, so no float appears.

Step 3

Calls at the boundaries: rides_left(335, 335) gives 1, rides_left(334, 335) gives 0, rides_left(0, 335) gives 0, each one equal to the value worked out by hand.

CallExpectedObtainedVerdictrides_left(2000, 335)55passrides_left(335, 335)11passrides_left(334, 335)00passrides_left(0, 335)00passFour calls, the expected value worked out by hand first

Why

A balance equal to the fare is the boundary that a wrong formula misses; one cent less must give 0.

Step 4

print(rides_left(2000, 335)) prints 5. With the arguments swapped, rides_left(335, 2000) gives 0, with no error.

Why

Nothing checks the order of the arguments but the writer: the values worked out by hand beforehand catch a swap.

The conclusion, written out

“rides_left(2000, 335) gives back 5: the card pays for 5 full rides, and 2000 - 1675 = 325 cents are left.”

The classic mistake on this problem: Writing print(rides) in place of return rides: the function displays 5 and gives back None, and rides_left(2000, 335) + 1 stops with a TypeError.

Learn by heart

  • • def defines; the body runs at each call.
  • • Arguments go to the parameters by position: read the header before each call.
  • • return gives back a value and ends the call; no return means None.
  • • print displays, return gives back: a function used in a calculation returns.
  • • Parameters and names assigned in a function are local and vanish at the return.
  • • A name assigned in a function is local in the whole function: UnboundLocalError if it is read first.
  • • A number parameter is a copy; an array parameter is the caller's array.
  • • A returned value is lost unless it is stored, v = f(x), or used at once, print(f(x)).

Frequently asked questions

What is the difference between print and return in a Python function?

print displays a value on the screen and gives nothing to the program, while return sends the value back to the line that called the function, where it can be stored or used in a calculation. A function that only prints gives back the special value None, so using its result in a sum stops the program with a TypeError.

Why does my Python function return None?

Because the call reached the end of the body without meeting a return statement. This happens when the function prints its result instead of returning it, or when a return sits inside an if whose condition was false. Follow each path through the function and make sure every one of them ends with a return of the value you want.

What does UnboundLocalError mean in Python?

It means the function reads a variable that Python treats as local, because it is assigned somewhere in the same function, before that variable has received a value. The usual case is a line such as count equals count plus one inside a function, with count defined outside. Pass the value as a parameter and return the new value, or declare the name global.

Does a Python function change a list passed as an argument?

Yes, if the function assigns to the cells of the list: the parameter refers to the caller's list itself, so every change of a cell is seen by the caller. If the function only gives its parameter a new list, the caller's list is not touched. To protect the original, pass a copy made with a full slice.

What is the difference between a local and a global variable in Python?

A global variable is created by the main program and can be read anywhere. A local variable is a parameter or a name assigned inside a function: it exists only while that call runs and disappears at the return. Two variables with the same name, one global and one local, are two different variables, and changing the local one leaves the global one as it was.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Functions, parameters and scope, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 10 corrected exercises
  • 100 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Revision sheet published at www.letuteurscientifique.ca/en/fiches/ics3u-functions-parameters-scope. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session.

Site by Studio Squalli