ICS3U Computer Science • Ontario Grade 11

Corrected exercises: functions, parameters and scope (ICS3U)

Exercises: functions, parameters and scope (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 10 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-functions-parameters-scope

These ten corrected exercises cover the seventh chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: writing subprograms.

What the set covers, the traps it targets

You define functions with parameters, pass arguments in the order of the header, send a value back with return, tell local variables from global ones, pass a one-dimensional array to a function, complete a program from a skeleton, apply a formula in a function (hypotenuse, primes, area and circumference of a circle), and cut a long program into functions drawn on a structure chart.

The code is in Python 3; traces of calls, scope and parameter passing are reasoned the same way in any language, and a line of the solutions says where Java behaves differently.

By the end, you can trace nested calls and describe the call stack (exercise 1), see why a function that prints gives back None, on a shipping cost (exercise 2), say which names exist inside and outside a function, on a student's pay (exercise 3), repair an UnboundLocalError on the tickets of a school dance (exercise 4), and predict what a function changes in an array of pixels it receives (exercise 5). Part B completes a skeleton that computes distances on a map grid with hypotenuse() (exercise 6), catches two arguments passed in the wrong order on grocery unit prices (exercise 7), corrects five statements (exercise 8), corrects is_prime() and chooses the test calls that reveal its bugs (exercise 9), and cuts the program of a trampoline spec sheet into functions (exercise 10).

The thread of the set: 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, and, apart from a global statement, only the cells of an array it receives carry a change back. Five traps are named in the solutions: (1) a function that prints instead of returning, whose result is None, exercises 2, 5, 6 and 8; (2) a local variable used outside its function, a NameError, exercises 3 and 8; (3) a global variable assigned in a function without global, an UnboundLocalError, exercise 4; (4) two number arguments passed in the wrong order, with no error and a wrong result, exercises 6, 7 and 8; (5) an array passed as a parameter and changed in the function, changed for the caller as well, exercises 5 and 8. Also treated: the order in which nested calls run (1), a number parameter changed in the function that leaves the caller's variable alone (3), a returned value that is not stored (4), a parameter given a new array (5), a return in the else of a loop that ends the function after one pass (9), and a diameter passed where a radius is expected (10).

No calculator is needed: every value is a trace worked out by hand, and the values that involve math.pi are asked as multiples of math.pi, as on a unit test.

  • 10 corrected exercises • 100 points • 150 minutes
  • Self-checking, 81 answers
  • No calculator
Start exercise 1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • def only defines a function; its body runs at each call, and the call is replaced by the value of return.
  • • The arguments are copied into the parameters by position: the first argument goes to the first parameter.
  • • return sends a value back and ends the call; a function that reaches its end without return gives back None.
  • • print displays a value on the screen; it gives nothing back to the program.
  • • Parameters and names assigned in a function are local: they disappear when the call ends.
  • • A name assigned in a function is local in the whole function; global name lets the function change a global variable.
  • • A number parameter receives a copy of the value: changing it changes nothing for the caller.
  • • An array parameter refers to the caller's array: t[i] = ... changes it, t = ... does not.

Part A: the basics (/50)

Exercise 1: Tracing calls: the order in which the lines run

8 answers to check

A def statement only defines a function: its body runs when the function is called, and every call ends by sending its value back to the place of the call. Trace the program below without running it.

Python
def square(n):                      # line 1
    print('square of', n)           # line 2
    return n * n                    # line 3
def sum_of_squares(a, b):           # line 4
    total = square(a) + square(b)   # line 5
    return total                    # line 6
result = sum_of_squares(3, 4)       # line 7
print(result)                       # line 8
print(square(square(2)))            # line 9
  • a) How many lines does the program print? What is the first of them?
  • b) What value does square(a) return the first time line 5 calls it? What does line 8 print?
  • c) What does line 9 print, line after line?
  • d) How many times does line 2 run in the whole program?
  • e) At the moment line 2 runs for the first time, which calls have started and not yet finished? What value does n hold in the call that is running?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 6 lines; the first is square of 3
  • b) 9; 25
  • c) square of 2, then square of 4, then 16
  • d) 4 times
  • e) the main program, sum_of_squares(3, 4) and square(3); n = 3

Lines 1 to 6 only define the two functions: nothing is printed and no body runs. The program starts its work at line 7, and each call is followed into the body of the function, then back to the place of the call with the value returned.

a)

Line 7 calls sum_of_squares(3, 4). Line 5 calls square(3), whose line 2 prints square of 3, then square(4), which prints square of 4. total is 9 + 16 = 25.

Line 8 prints 25. Line 9 prints three lines (part c).

The program prints 2 + 1 + 3 = 6 lines, and the first is square of 3.

Pitfall: starting the trace at line 1 and printing something for a def. A def creates the function, it does not call it.

b)

The first call of line 5 is square(a) with a = 3: n receives 3 and line 3 returns 3 * 3 = 9.

The second call, square(4), returns 16, and total = 9 + 16 = 25 is returned by line 6 to line 7: result holds 25, which line 8 prints.

c)

A call written inside another call runs first, since its value is the argument of the outer call.

square(2) prints square of 2 and returns 4; then square(4) prints square of 4 and returns 16; print displays 16.

Pitfall: reading the line from left to right and printing square of 4 first. The outer square cannot start before it knows its argument.

d)

Line 2 runs once per call of square: twice from line 5 (for 3 and for 4), twice from line 9 (for 2 and for 4). 4 times.

e)

The main program is stopped at line 7, waiting for sum_of_squares(3, 4); that call is stopped at line 5, waiting for square(3); square(3) is the one running, with n = 3.

The figure shows this call stack: the call running sits on top, and each call below it waits for the value of the call above it. When square(3) returns 9, its frame is removed and sum_of_squares goes on from line 5.

square(3): n = 3sum_of_squares(3, 4): a = 3, b = 4main program: waits at line 7Call stack while line 2 runs for the first timetop: running nowbottom: waiting

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Exercise 2: print or return: a shipping cost that comes back as None

7 answers to check

An online store charges 8 dollars per parcel plus 3 dollars per kilogram. The function shipping_cost was meant to give back the cost, so that the program can add it to the price of an order of 25 dollars.

Python
def shipping_cost(weight):      # line 1
    cost = 8 + 3 * weight       # line 2
    print('Cost:', cost)        # line 3
order = shipping_cost(2)        # line 4
print(order)                    # line 5
total = 25 + shipping_cost(5)   # line 6
print(total)                    # line 7
  • a) What do lines 4 and 5 print?
  • b) What value does order hold after line 4?
  • c) What happens when Python reaches line 6?
  • d) Line 3 is replaced by return cost. What do lines 5 and 7 print now? In this new version, what does a line shipping_cost(4) written on its own display?
  • e) A second function is meant to give a label: def size_label(weight): with the body if weight > 10: return 'heavy'. What does print(size_label(4)) display?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Cost: 14, then None
  • b) None
  • c) Cost: 23 is printed, then a TypeError stops the program
  • d) 14 and 48; nothing
  • e) None

print sends text to the screen; return sends a value back to the place of the call. A function that reaches its end without a return gives back the special value None, and the caller has nothing to compute with.

a)

Line 4 calls shipping_cost(2): cost = 8 + 3 * 2 = 14, and line 3 prints Cost: 14.

The function ends without return, so the call is worth None, stored in order. Line 5 prints None.

b)

order holds None, not 14: the 14 went to the screen and nowhere else.

Pitfall: reading Cost: 14 on the screen and believing the program has the number. A display is not a value.

c)

Line 6 calls shipping_cost(5) first: cost = 8 + 15 = 23, and Cost: 23 is printed.

Then Python computes 25 + None and stops: TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'. Line 7 never runs.

The message names NoneType: a None in a calculation usually points to a function without return.

d)

With return cost, shipping_cost(2) is worth 14: line 4 prints nothing and line 5 prints 14.

Line 6 computes 25 + 23 = 48, and line 7 prints 48.

shipping_cost(4) alone computes 20 and sends it back to a line that does not store it: nothing is displayed, and the 20 is lost.

e)

For weight = 4, the condition weight > 10 is False, the return is skipped, and the function reaches its end: it gives back None, which print displays.

Every path through a function needs its return: here a second line, return 'light', after the if.

In Java, a method declared to return a String that can end without return does not compile; Python only finds out when the call runs.

Exercise 3: Local and global names: what exists outside the function

6 answers to check

A student job pays 16 dollars an hour on weekdays, stored in the global variable rate. To test the weekend rate of 20 dollars an hour, a student adds line 3 to the function pay.

Python
rate = 16                   # line 1
def pay(hours):             # line 2
    rate = 20               # line 3
    amount = hours * rate   # line 4
    return amount           # line 5
print(pay(3))               # line 6
print(rate)                 # line 7
print(amount)               # line 8
  • a) What does line 6 print?
  • b) What does line 7 print?
  • c) What happens at line 8?
  • d) Line 3 is deleted, the rest unchanged. What does line 6 print now?
  • e) Lines 3 and 8 are deleted, and pay receives a second parameter: def pay(hours, rate): with the body amount = hours * rate, then rate = 0, then return amount. The main program runs print(pay(3, rate)), then print(rate). What do these two lines print?

Type your answers, the page tells you right or wrong 0/6

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 60
  • b) 16
  • c) NameError: name 'amount' is not defined
  • d) 48
  • e) 48, then 16

Each call creates a frame of its own: its parameters and every name assigned in its body are local to it, and they disappear when the call ends. A name used in a function without being assigned there is looked up among the global names.

a)

Line 3 assigns rate inside pay: this creates a local rate = 20, distinct from the global one. hours = 3, so amount = 3 * 20 = 60, and line 6 prints 60.

b)

Line 3 changed the local rate only. The global rate still holds 16, and line 7 prints 16.

The figure shows the two frames while line 5 runs: two names rate, one in each frame.

c)

amount was local to the call pay(3), and that frame was erased at the return. Line 8 stops the program: NameError: name 'amount' is not defined.

To use the value outside, store what the function returns: amount = pay(3).

Pitfall: thinking that a variable created in a function stays available after the call.

In Java, a variable used outside the block where it is declared is refused when the program is compiled, before any run.

d)

Without line 3, rate is not assigned in pay, so line 4 reads the global rate, 16: 3 * 16 = 48.

Reading a global variable in a function is allowed; assigning it is the subject of the next exercise.

e)

The call pay(3, rate) copies the value 16 of the global rate into the parameter rate, a local name: amount = 3 * 16 = 48, which is printed.

rate = 0 changes the parameter, a local name, and the global rate keeps 16: the second line prints 16.

A number parameter receives a copy of the value: changing it inside the function leaves the caller's variable alone.

Global namesrate = 16Frame of pay(3)hours = 3rate = 20amount = 60At return, pay(3) gives back 60 and its frame is erased: amount no longer exists.While line 5 runs, two names rate exist, one in each frame

Exercise 4: Changing a global variable inside a function: UnboundLocalError

7 answers to check

The student council sells 120 tickets for the school dance. The program keeps the number of tickets left in a global variable, and a function sell is meant to take each sale away from it.

Python
tickets_left = 120                    # line 1
def sell(n):                          # line 2
    tickets_left = tickets_left - n   # line 3
    return tickets_left               # line 4
print(sell(15))                       # line 5
  • a) What happens when line 5 runs? On which line is the error raised?
  • b) Why?
  • c) Version A adds the line global tickets_left at the top of the body of sell. The main program then runs sell(15), then sell(30), then print(tickets_left). What does it print?
  • d) Version B has no global variable inside the function: def sell(left, n): with the single line return left - n. The main program runs tickets_left = sell(tickets_left, 15), then sell(tickets_left, 30) on its own line, then print(tickets_left). What does it print?
  • e) Version B receives a guard: if n > left, it prints Only, left, left and returns left unchanged. From 120 tickets, the main program runs tickets_left = sell(tickets_left, 100), then tickets_left = sell(tickets_left, 25). What does tickets_left hold at the end? Which version can be tested on its own, by calls with chosen values?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) UnboundLocalError; line 3
  • b) the assignment on line 3 makes tickets_left local to the whole function, and its right side reads it before it has a value
  • c) 75
  • d) 105
  • e) 20; version B

Python decides once for the whole function whether a name is local: a name assigned anywhere in the body is local everywhere in the body, unless a global statement says otherwise.

a)

Line 5 calls sell(15). Line 3 computes tickets_left - n, and Python stops: UnboundLocalError: cannot access local variable 'tickets_left' where it is not associated with a value. The error is raised on line 3, and nothing is printed.

b)

Line 3 assigns tickets_left, so tickets_left is a local name of sell, for the whole body. Its right side reads this local name, which has no value yet: the global 120 is not used.

Pitfall: thinking that tickets_left = tickets_left - n reads the global name and writes it back. Reading alone would use the global name (exercise 3 d); the assignment changes the rule for the whole function.

c)

global tickets_left tells Python that the name in sell is the global one. sell(15) brings it to 105, sell(30) to 75, and print(tickets_left) prints 75.

In Java, a method changes a static field of its class directly, without any keyword.

d)

sell(tickets_left, 15) receives 120 and returns 105, which the assignment stores: tickets_left holds 105.

sell(tickets_left, 30) returns 75 to a line that does not store it: the 75 is lost, and print(tickets_left) prints 105.

The table follows the main program line by line: a value returned that no assignment stores is lost.

e)

First call: 100 > 120 is False, so the function returns 120 - 100 = 20, stored in tickets_left.

Second call: 25 > 20 is True, so the function prints Only 20 left and returns left, 20. tickets_left holds 20 at the end.

Version B depends only on its arguments: sell(120, 100) gives 20 and sell(20, 25) gives 20, whatever the rest of the program holds. Version A reads and changes a global variable, so each test call changes the starting point of the next one.

Passing the value in and returning the new one is the usual design; global is kept for the rare case where several functions share one state.

Python
def sell(left, n):
    # gives back the tickets left after a sale of n tickets
    if n > left:
        print('Only', left, 'left')
        return left
    return left - n
tickets_left = 120
tickets_left = sell(tickets_left, 100)
tickets_left = sell(tickets_left, 25)
print(tickets_left)
Main programReturnedtickets_lefttickets_left = 120120tickets_left = sell(tickets_left, 15)105105sell(tickets_left, 30)75, lost105print(tickets_left)prints 105Version B, line by line

Exercise 5: An array passed to a function: brightening a row of pixels

6 answers to check

In a grayscale image, each pixel is a whole number from 0 (black) to 255 (white), and one row of the image is a one-dimensional array, a list in Python. The function brighten adds amount to every pixel of a row, and min keeps each value at 255 or less. The function reset is meant to turn a row black.

Python
def brighten(row, amount):                   # line 1
    for i in range(len(row)):                # line 2
        row[i] = min(row[i] + amount, 255)   # line 3
def reset(row):                              # line 4
    row = [0] * len(row)                     # line 5
pixels = [200, 90, 250, 30]                  # line 6
brighten(pixels, 40)                         # line 7
print(pixels)                                # line 8
reset(pixels)                                # line 9
print(pixels)                                # line 10
x = brighten(pixels, 10)                     # line 11
print(x, pixels[0])                          # line 12
  • a) What does line 8 print?
  • b) brighten has no return. Why does pixels change at line 7?
  • c) What does line 10 print?
  • d) What does line 12 print?
  • e) Which body of reset turns the caller's row black? With that body, what value of pixels[0] does line 12 print?

Type your answers, the page tells you right or wrong 0/6

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) [240, 130, 255, 70]
  • b) row and pixels are two names of one array, and line 3 changes its cells
  • c) [240, 130, 255, 70]
  • d) None 250
  • e) for i in range(len(row)): row[i] = 0; 10

When an array is passed to a function, the parameter receives the same array, not a copy: an assignment to a cell, row[i] = ..., changes that array for every name that refers to it. An assignment to the name itself, row = ..., only makes the local name refer to another array.

a)

brighten(pixels, 40): 200 + 40 = 240, 90 + 40 = 130, min(250 + 40, 255) = min(290, 255) = 255, 30 + 40 = 70.

Line 8 prints [240, 130, 255, 70].

b)

The parameter row refers to the array of pixels: both names lead to the same four cells, as the figure shows. Line 3 writes into those cells, and pixels sees the change.

Pitfall: believing that a function without return cannot change anything outside. Through the cells of an array it receives, it can.

In Java, an array parameter also refers to the caller's array: the same result.

c)

Line 5 builds a new array [0, 0, 0, 0] and gives it the local name row. The array of pixels is not touched, and the new array is lost at the return.

Line 10 prints [240, 130, 255, 70], unchanged.

d)

brighten(pixels, 10) changes the cells: min(250, 255) = 250, 140, min(265, 255) = 255, 80. It has no return, so x holds None.

Line 12 prints None 250.

e)

An assignment to the cells reaches the caller's array: for i in range(len(row)): row[i] = 0.

row = [0, 0, 0, 0] repeats the mistake of line 5, and for p in row: p = 0 changes a loop variable that holds a copy of each value.

With the correct body, line 9 turns pixels into [0, 0, 0, 0], line 11 brightens it to [10, 10, 10, 10], and line 12 prints None 10.

240130255700123pixelsrowmain programin brighten0000rowin resetnew array, lost at returnone array, two names

Part B: problems and reasoning (/50)

Exercise 6: Completing a skeleton: distances on a map grid with hypotenuse()

9 answers to check

A map app places each building on a grid where one unit is a city block of 100 m (figure). The straight-line distance between two points is the hypotenuse of a right triangle whose legs are the differences of their coordinates. The teacher gives the skeleton below, with line 4 to complete.

024681012140246School (2, 1)Library (5, 5)Arena (14, 6)One unit of the grid is a city block of 100 m
Python
import math                                                   # line 1
def hypotenuse(a, b):                                         # line 2
    # length of the hypotenuse, legs a and b                  # line 3
    ________________________________                          # line 4
def distance(x1, y1, x2, y2):                                 # line 5
    # straight-line distance in metres, 1 grid unit = 100 m   # line 6
    return hypotenuse(x2 - x1, y2 - y1) * 100                 # line 7
print(distance(2, 1, 5, 5))                                   # line 8
  • a) Which line completes line 4?
  • b) With that line, what does hypotenuse(12, 5) return? What does line 8 print?
  • c) What does distance(14, 6, 2, 1) give, from the arena to the school? Does the order of the two points change the result?
  • d) For the school and the library, a student writes distance(2, 5, 1, 5): the two x first, then the two y. What does the call give? Does Python report an error?
  • e) Walking follows the streets of the grid: walk(x1, y1, x2, y2) returns (abs(x2 - x1) + abs(y2 - y1)) * 100. The teacher's convention: a comment under each header says what the function gives back, with its unit. Which comment follows it? What does walk(2, 1, 5, 5) give?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) return math.sqrt(a ** 2 + b ** 2)
  • b) 13.0; 500.0
  • c) 1300.0; no
  • d) 100.0; no error
  • e) # walking distance in metres, along the streets of the grid; 700

A function completed from a skeleton keeps the header it was given: its name, its parameters in their order, and what the comment promises it gives back. distance relies on hypotenuse, so hypotenuse must return its value.

a)

return math.sqrt(a ** 2 + b ** 2) gives back the square root of the sum of the squares, the formula of the hypotenuse.

With print(...) in its place, hypotenuse displays 5.0 and gives back None, and line 7 stops on None * 100 with a TypeError.

return math.sqrt(a ** 2) + math.sqrt(b ** 2) gives back a + b for positive legs, that is 7 for 3 and 4: the walking distance of part e, not the straight line.

b)

hypotenuse(12, 5) = math.sqrt(144 + 25) = math.sqrt(169) = 13.0, a float, since math.sqrt always gives back a float.

Line 8: x2 - x1 = 5 - 2 = 3 and y2 - y1 = 5 - 1 = 4, hypotenuse(3, 4) = math.sqrt(25) = 5.0, and 5.0 * 100 = 500.0, which is printed.

c)

From the arena to the school: 2 - 14 = -12 and 1 - 6 = -5. The squares are 144 and 25, as for 12 and 5: 13.0 * 100 = 1300.0 metres.

Swapping the two points changes the signs of the differences, and squaring removes the signs: the order of the two points does not change the result.

d)

The parameters are matched by position: x1 = 2, y1 = 5, x2 = 1, y2 = 5. Then x2 - x1 = -1 and y2 - y1 = 0, hypotenuse(-1, 0) = 1.0, and the call gives 100.0 metres instead of 500.0.

Python reports no error: four numbers were given for four parameters.

Pitfall: passing the arguments in another order than the header. A value worked out by hand beforehand shows the mistake: 100 m between two buildings that are three blocks apart in x cannot be right.

e)

The comment that follows the convention says what is given back and its unit: # walking distance in metres, along the streets of the grid. « uses abs twice » describes the code, « walk function » repeats the name.

walk(2, 1, 5, 5) = (abs(3) + abs(4)) * 100 = 700 metres, more than the 500 m in a straight line, as expected for a path that turns a corner.

Exercise 7: Two arguments in the wrong order: unit prices at the grocery store

11 answers to check

A grocery app compares packages by their price per 100 g. The table gives two boxes of the same cereal. Each function below has two or four number parameters, and Python matches the arguments of a call to the parameters by their position.

PackageMassPriceBox A750 g6.00 dollarsBox B1200 g9.00 dollarsTwo boxes of the same cereal
Python
def unit_price(price, grams):                                     # line 1
    # price per 100 g, in dollars                                 # line 2
    return price * 100 / grams                                    # line 3
def cheaper(price1, grams1, price2, grams2):                      # line 4
    # 1 if package 1 costs less per 100 g, else 2                 # line 5
    if unit_price(price1, grams1) < unit_price(price2, grams2):   # line 6
        return 1                                                  # line 7
    return 2                                                      # line 8
def basket(quantity, price):                                      # line 9
    # cost of several identical packages, in dollars              # line 10
    return quantity * price                                       # line 11
  • a) Give unit_price(6.00, 750), unit_price(9.00, 1200) and cheaper(6.00, 750, 9.00, 1200).
  • b) A student writes unit_price(750, 6.00). What does the call give? Does Python report an error?
  • c) What does cheaper(6.00, 750, 1200, 9.00) return, with the two arguments of box B swapped? Is it the right answer?
  • d) basket(3, 6.00) and basket(6.00, 3) give the same value. Which value? Does comparing these two calls show which one has its arguments in the right order?
  • e) What does unit_price(grams=750, price=6.00) give? How does Python match the arguments of the call unit_price(750, 6.00) to the parameters?

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 0.8; 0.75; 2
  • b) 12500.0; no error
  • c) 1; no, box B is cheaper
  • d) 18.0; no
  • e) 0.8; by position: price receives 750 and grams receives 6.00

In a call, the first argument goes to the first parameter, the second to the second, and so on: in a call without named arguments, Python does not look at the names of the variables passed or at the size of the values. Two numbers in the wrong order raise no error when the formula accepts them.

a)

unit_price(6.00, 750) = 6.00 * 100 / 750 = 600 / 750 = 0.8 dollar per 100 g.

unit_price(9.00, 1200) = 900 / 1200 = 0.75 dollar per 100 g.

0.8 < 0.75 is False, so cheaper returns 2: box B, the large one, costs less per 100 g.

b)

price receives 750 and grams receives 6.00: 750 * 100 / 6.00 = 12500.0 dollars per 100 g, with no error.

Pitfall: swapping two number arguments. The program runs and gives an absurd value, which a check of the order of magnitude catches: a cereal does not cost thousands of dollars per 100 g.

c)

Line 6 compares unit_price(6.00, 750) = 0.8 with unit_price(1200, 9.00) = 120000 / 9.00, about 13333.3. 0.8 < 13333.3 is True, so cheaper returns 1.

The right answer is 2 (part a): the swap inside one call changes the decision, still without any error.

d)

3 * 6.00 = 6.00 * 3 = 18.0 dollars: a product gives the same value in either order.

This pair of calls cannot show the mistake, since both give 18.0. A call that passes is no proof that the arguments are in the right order: for unit_price, the swap changes the value; for basket, it does not, and the code stays fragile the day the formula changes.

e)

With named arguments, Python matches each value to the parameter of the same name, whatever their order: price = 6.00 and grams = 750, and the call gives 0.8.

Without names, the match is by position: in unit_price(750, 6.00), price receives 750 and grams receives 6.00.

Java matches the arguments by position too, and has no named arguments: the order of the header is the guide.

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written by a student revising this chapter. Say whether it is true or false, then answer the question that follows it. Each false statement is corrected in the solution.

  • a) « A function that ends with print(result) gives result back to the caller. » For def double(x): with the body print(x * 2), what does y hold after y = double(4)?
  • b) « A variable created inside a function can be used by the main program once the call has ended. » After def setup(): with the body z = 5, then the call setup(), what does print(z) give?
  • c) « If two arguments are swapped in a call, Python reports an error when the result makes no sense. » For def ratio(a, b): with the body return a / b, what does ratio(2, 8) give?
  • d) « A function that receives an array and changes one of its cells changes the caller's array. » After def bump(t): with the body t[0] = t[0] + 1, then a = [7, 3], bump(a) and bump(a), what is a[0]?
  • e) « A function can contain several return statements; each call runs at most one of them. » For def sign(x): with the body if x < 0: return -1, then if x == 0: return 0, then return 1, give sign(-3) + sign(0) + sign(12).

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False; None
  • b) False; NameError
  • c) False; 0.25
  • d) True; 9
  • e) True; 0

Each statement is settled by one call worked out to the end: what goes in, which lines run, what comes back.

a)

False. print(x * 2) displays 8 and the function ends without return: y holds None.

Correct statement: « A function gives result back to the caller with return result; print only displays it. »

b)

False. z is local to the call setup(), and its frame is erased at the return: print(z) stops the program with NameError: name 'z' is not defined.

Correct statement: « A value computed in a function reaches the main program through return and an assignment, z = setup() with return 5 in the body. »

c)

False. ratio(2, 8) = 2 / 8 = 0.25 instead of the 4.0 of ratio(8, 2), and Python reports nothing: it checks the number of arguments, never their meaning.

Correct statement: « Swapped arguments raise no error when the formula accepts them; a value worked out by hand reveals the mistake. »

d)

True. t and a refer to the same array, so t[0] = t[0] + 1 changes a[0]: 7, then 8, then 9.

The condition matters: an assignment to the name, t = [0, 0], would have changed nothing for a.

e)

True. The first return reached ends the call: sign(-3) stops at return -1, sign(0) at return 0, sign(12) at return 1. -1 + 0 + 1 = 0.

A call can also run none of them, when its path reaches the end of the body: it then gives back None (exercise 2 e).

Exercise 9: Writing is_prime() and choosing the calls that test it

8 answers to check

A whole number is prime when it has exactly two divisors, 1 and itself: 2, 3, 5, 7, 11 and so on; 1 is not prime, since it has one divisor only. A student writes is_prime and a second function that counts the primes from low to high. The program runs without any error message.

Python
def is_prime(n):                                       # line 1
    for d in range(2, n):                              # line 2
        if n % d == 0:                                 # line 3
            return False                               # line 4
        else:                                          # line 5
            return True                                # line 6
    return True                                        # line 7
def count_primes(low, high):                           # line 8
    count = 0                                          # line 9
    for n in range(low, high + 1):                     # line 10
        if is_prime(n):                                # line 11
            count = count + 1                          # line 12
    return count                                       # line 13
print(is_prime(9), is_prime(1), count_primes(1, 60))   # line 14
  • a) What does is_prime(9) return? How many values of d does the loop try before the function returns?
  • b) What does is_prime(1) return? Why?
  • c) What does count_primes(1, 60) give in this version?
  • d) The student deletes lines 5 and 6 and starts the body with if n < 2: return False. What do count_primes(1, 60) and count_primes(50, 100) give now?
  • e) Which three test calls, run on the first version, reveal both of its bugs?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) True; 1 value
  • b) True; range(2, 1) is empty, so line 7 returns True
  • c) 31
  • d) 17 and 10
  • e) is_prime(1), is_prime(9) and is_prime(13)

One divisor found is enough to answer False, at once; True can only be answered after the loop, once every d has been tried. A return placed in the else of the loop answers after the first pass.

a)

d = 2: 9 % 2 = 1, not 0, so the else runs and line 6 returns True. The loop tries one value of d, and 3, the divisor of 9, is never reached.

The table compares the two versions pass by pass.

Pitfall: a return in both branches of an if inside a loop. The loop then runs once at most, whatever its range.

b)

range(2, 1) is empty: the loop does not run, and line 7 returns True. is_prime(2) also skips the loop, and True is right for 2; for 1 it is wrong.

c)

The first version answers True for 1 and 2 (empty loop), True for every odd number from 3 (the first pass tests 2 only), and False for every even number from 4.

From 1 to 60: 1, 2, and the 29 odd numbers from 3 to 59, that is 31.

d)

The corrected version, below, tries every d from 2 to n - 1 before answering True, and answers False for n < 2.

From 1 to 60: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, that is 17 primes.

From 50 to 100: 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, that is 10 primes.

e)

On the first version, is_prime(1) gives True (bug of part b) and is_prime(9) gives True (bug of part a), while is_prime(13) gives True, the right answer.

is_prime(2), is_prime(3) and is_prime(7) are prime: the first version answers True, the right answer each time, and reveals nothing. is_prime(4), is_prime(10) and is_prime(17) also get the right answers: 4 and 10 are even, and 17 is prime.

A useful test call is one where the expected answer, worked out by hand, differs from what a likely bug gives: 1, and an odd number that is not prime.

Python
def is_prime(n):
    # True if n is prime, False otherwise
    if n < 2:
        return False
    for d in range(2, n):
        if n % d == 0:
            return False
    return True
d9 % dStudent versionCorrected version21else: return Truenext value of d30never reachedreturn Falseis_prime(9), one row per pass of the loop

Exercise 10: Cutting a program into functions: the spec sheet of round trampolines

9 answers to check

A store sells round trampolines by the diameter of their frame (figure). For each model, its spec sheet gives the diameter in metres, the area inside the frame in square metres and the length of the safety pad that covers the frame, in metres. The program below prints the three lines of the sheet, starting with 3.0 7.07 9.42.

diameter ddashed: radius r = d / 2frame, covered by the padinside: the area of the mat
Python
import math                                                         # line 1
d = 3.0                                                             # line 2
print(d, round(math.pi * (d / 2) ** 2, 2), round(math.pi * d, 2))   # line 3
d = 3.7                                                             # line 4
print(d, round(math.pi * (d / 2) ** 2, 2), round(math.pi * d, 2))   # line 5
d = 4.3                                                             # line 6
print(d, round(math.pi * (d / 2) ** 2, 2), round(math.pi * d, 2))   # line 7
  • a) The same formulas appear three times. A student cuts the program into three functions: circle_area(radius), circumference(radius), and spec_line(diameter), which computes the radius and prints one line; the main program calls spec_line once per model. Which structure chart describes this version?
  • b) When the main program runs spec_line(3.7), which argument does spec_line pass to circle_area? How many times is circle_area called while the whole program runs?
  • c) circle_area(1.5) gives back math.pi times which number? Same question for circumference(1.5).
  • d) In spec_line, a student writes circle_area(diameter) instead of circle_area(radius). Does Python report an error? By what factor is each area too large?
  • e) The store now wants the areas rounded to one decimal. How many lines change in the long program? In the version with functions?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) the main program calls spec_line; spec_line calls circle_area and circumference
  • b) 1.85; 3 times
  • c) 2.25; 3
  • d) no error; 4
  • e) 3 lines; 1 line

Cutting a program into functions gives each formula one name and one place in the code. A structure chart shows who calls whom: each line goes from a caller down to the function it calls, and a function that appears once in the chart is written once in the code.

a)

The main program calls spec_line; spec_line calls circle_area and circumference, which call nothing. The figure draws this chart, and the code of this version is given below.

The main program does not call circle_area itself: it only knows diameters, and spec_line turns a diameter into a radius.

b)

spec_line(3.7) computes radius = 3.7 / 2 = 1.85 and calls circle_area(1.85).

spec_line is called three times, once per model, and each call calls circle_area once: 3 calls.

c)

circle_area(1.5) = math.pi * 1.5 ** 2 = math.pi * 2.25: the number is 2.25. Rounded, 7.07, the first area of the sheet.

circumference(1.5) = 2 * math.pi * 1.5 = math.pi * 3, the same as math.pi * d for d = 3.0 in the long program: the number is 3.

d)

circle_area(diameter) runs without any error: a diameter is a number like a radius.

The radius used is twice too large, and the area grows with its square: 2 ** 2 = 4 times too large. For 4.3 m, the sheet would print 58.09 instead of 14.52.

Pitfall: passing a value whose meaning is not the one the header says. The comment under the header, « radius », is there to prevent it.

e)

In the long program, the rounding of the area is written on lines 3, 5 and 7: 3 lines change, and forgetting one leaves a sheet with two kinds of rounding.

In the version with functions, the round of the area is written once, in spec_line: 1 line changes. One formula in one place is what modularity buys.

Python
import math
def circle_area(radius):
    # area of a circle, in the square of the unit of radius
    return math.pi * radius ** 2
def circumference(radius):
    # perimeter of a circle, in the unit of radius
    return 2 * math.pi * radius
def spec_line(diameter):
    # prints the diameter, the area inside the frame, the length of pad
    radius = diameter / 2
    print(diameter, round(circle_area(radius), 2), round(circumference(radius), 2))
for d in [3.0, 3.7, 4.3]:
    spec_line(d)
main programspec_line(diameter)circle_area(radius)circumference(radius)Structure chart: each line goes from a caller down to the function it calls
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, 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. Exercise set published at www.letuteurscientifique.ca/en/exercices/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: parameters, return and scope come back in every program you write after this unit.

Site by Studio Squalli