Exam practice
Every question from the end of every unit, with hints and answers to open. After you check an answer, mark how you did, and come back to the ones you didn’t get.
10 questions
Unit 4 · Functions: Building Blocks of Programs
What is decomposition? Show how you would decompose the job “make a birthday card program that draws a cake and writes a message”, at least two levels deep, and say which parts you would make functions with parameters.
Answer
Decomposition is breaking a big job into smaller parts, and those into smaller parts, until each one is easy to do.
- Draw the cake: the base (a rectangle), the icing (a filled rectangle on top), the candles (one small rectangle and a flame, several times).
- Write the message: move to a place under the cake, write the words.
rectangle(width, height) is needed for the base, the icing and every candle, so it should be a function with parameters. candle(x) draws one candle at a place, called once for each candle (a loop can call it as many times as the person is old). message(text) writes any message, so the same program makes a card for anyone.
Explain the difference between a parameter and an argument, using def area(length, width): and area(5, 8).
Answer
A parameter is a name in the function’s definition that waits for a value: length and width. An argument is the value given when the function is called: 5 and 8. When area(5, 8) runs, the arguments go into the parameters in order: 5 into length, 8 into width. The same function can be called again with other arguments, and the parameters get those values instead.
Write the output of this program, and explain the order in which its lines run.
def greet(name): print("Namaste,", name) print("Welcome!") print("Start")greet("Dolma")greet("Bishal")print("End")Answer
Output
StartNamaste, DolmaWelcome!Namaste, BishalWelcome!EndPython reads lines 1 to 3 and remembers greet, without running it. Line 5 prints Start. Line 6 calls greet with "Dolma": Python jumps to line 1, puts "Dolma" into name, runs lines 2 and 3, then goes back to line 7. Line 7 does the same with "Bishal" and goes back to line 8, which prints End.
What is the difference between print and return in a function? Write two versions of a function square_of(n), one with each, and show which one can be used in total = square_of(3) + square_of(4).
Answer
print shows a value on the screen, for a person; the function still gives back None. return gives the value back to the line that called the function, so the program can use it, and ends the function.
def square_of(n): return n * n total = square_of(3) + square_of(4)print(total)Output
25With print(n * n) in place of the return, the two calls would print 9 and 16 but each give back None, and None + None stops with a TypeError. Only the return version works in a calculation.
Write a function is_even(n) that returns True if n is even and False if it is odd. Use it in a loop to print the even numbers from 1 to 10.
Answer
def is_even(n): return n % 2 == 0 for n in range(1, 11): if is_even(n): print(n)Output
246810n % 2 == 0 is already True or False, so it can be returned as it is. The if asks the function, and the function’s name makes the line read like a sentence: if n is even, print n.
A student wrote this to print the area of a rectangle plus 10, but it prints 40 and then stops with an error. Explain both, and correct the program.
def area(length, width): print(length * width) a = area(5, 8)print(a + 10)Answer
Line 4 calls area, which prints 40 and then gives back None, because it has no return; so a is None. Line 5 then works out None + 10, which stops with TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. The function should return its answer, not print it:
def area(length, width): return length * width a = area(5, 8)print(a + 10)Output
50Write a function highest(marks) that returns the highest number in a list, using Unit 2’s “highest so far” pattern, not Python’s max(). Test it with three lists, including one with a single item.
Answer
def highest(marks): best = marks[0] for i in range(1, len(marks)): if marks[i] > best: best = marks[i] return best print(highest([52, 38, 71, 45]))print(highest([90, 85, 60]))print(highest([33]))Output
719033best starts as the first mark, not 0, so the function also works for a list of negative numbers. The loop compares each other mark with the highest so far. For a list of one item, range(1, 1) gives no numbers, so the first mark is returned at once. (An empty list would stop with an IndexError at marks[0]: an edge test worth trying.)
Here is the documentation of a function in a module for drawing Nepal’s flag (a made-up example): draw_flag(height, x=0, y=0, outline=True). “Draws Nepal’s flag, height units tall, with the bottom of its pole at (x, y). If outline is False, the blue border is left out. Returns the flag’s width.” Answer:
- i.Which parameters must be given, and which are optional?
- ii.Write a call that draws a flag 200 units tall at (−100, −50).
- iii.Write a call that draws one 100 tall at (0, 0) without the border, and keeps its width in a variable.
Answer
- i.Only height must be given. x, y and outline have defaults (0, 0 and
True), so they may be left out. - ii.
draw_flag(200, -100, -50): the arguments go in order into height, x and y; outline staysTrue. - iii.
width = draw_flag(100, outline=False): x and y are left at 0, and the optional parameter outline is given by its name, asalign="center"was fort.write(). Because the function returns the width,=keeps it in width. (draw_flag(100, 0, 0, False)works too.)
A program for a shop prints a receipt line in seven places, each time with the same four lines of code but different item names and prices. Explain how a function would make the program better, giving at least three reasons.
Answer
Write the four lines once, as a function such as receipt_line(item, price), and replace each of the seven copies with a one-line call.
- Shorter and clearer: seven lines of calls instead of twenty-eight, and each call says what it does.
- One place to fix or change: if the receipt’s layout changes, or a bug is found, it is changed once, in the function, and all seven places follow. With copies, it is easy to fix six and forget the seventh.
- Testing: the function can be tested on its own with a few items and prices.
- Reuse: any new place in the program, or another program, can print a receipt line with one call.
Draw the flowchart of a function bigger(a, b) that returns the bigger of two numbers, and of a main program that inputs two numbers, calls it, and outputs the answer.
Answer
bigger(a, b): a rounded box bigger(a, b) → a decision a > b? → Yes: a rounded box Return a; No: a rounded box Return b.
The main program: Start → input INPUT x, y → procedure box big = bigger(x, y) → output OUTPUT big → Stop.
The function’s flowchart starts with its name and parameters instead of Start, and ends with Return instead of Stop: from Return it goes back to the procedure box that called it. In Python:
def bigger(a, b): if a > b: return a else: return b x = int(input("First number: "))y = int(input("Second number: "))big = bigger(x, y)print("The bigger one is", big)Output
First number: 17Second number: 42The bigger one is 42