Proof Academy · Python · Journey 06

Functions and program structure

Break a problem into named jobs and test the result of a function separately from input and output.

Lab and core lesson: 40–50 minutes, plus guided study · Builds on Strings, lists and records

01 · Understand and predict

Follow the data into and out of a function

A function gives a named job to part of a program. Parameters are the names in the definition. Arguments are the values supplied at a call. A return statement gives a result back to the caller and ends that call.

A local variable belongs to a call. Keeping input, processing and output separate lets you test a calculation with known arguments, then reuse it in a different interface. Printing inside a function displays text. It does not pass the printed value back to the caller.

def ticket_cost(people, price):
    cost = people * price
    return cost

first = ticket_cost(3, 4)
second = ticket_cost(2, 5)
print(first + second)

Worked trace

  1. The first call binds people to 3 and price to 4. It returns 12.
  2. The second call has fresh local values. It returns 10.
  3. The caller adds the two returned values and prints 22.
What value does the caller receive if the function uses print(cost) and has no return?

From code to machine. During a call the runtime keeps track of its local variables and where to return. These are runtime concepts. The hardware still runs machine instructions and reads and writes memory as the runtime carries out the call.

Guided study

Read it, trace it, test it

Describe a function’s contract

Before writing the body, decide what the function receives and what it gives back. For visit_cost(people, member), the first parameter represents a non-negative integer and the second represents a Boolean. The function returns the total as a number. It does not need to ask the user a question. The caller can read a value, convert it, and decide whether input() == "Y" before it calls the function. This division makes both parts easier to inspect and test.

A function definition names the steps. Python does not execute the body just because it has seen def. A call such as visit_cost(2, True) supplies two arguments. The names people and member are local to that call. Another call can use different values without changing the first result. Give function and parameter names that communicate their purpose, especially when several functions are used in the same file.

Trace the call and return

def booking_total(tickets, price):
    if tickets == 0:
        return 0
    total = tickets * price + 2
    return total

price = 5
first = booking_total(3, price)
second = booking_total(0, price)
print(first, second)
CallLocal ticketsLocal pricePathReturned value
First35Multiply, then add fee17
Second05Return immediately0

For the first call, the argument price is evaluated in the caller before the value is passed to the local parameter. Python returns 17 and assigns it to first. For the second call, the first return ends the function before it calculates a fee. The caller then prints 17 0. A trace column labelled “return” is useful when several functions call each other, because you can bring the value back to the exact expression waiting for it.

Avoid dependencies that make testing hard

A global value is defined outside a function. A function may read it, but a parameter is clearer when the value is an input to the calculation. For example, a delivery function that uses subtotal from outside its body only works as intended when someone has set that global value. Give the function a parameter instead, then test it with a few arguments you choose. To change a local variable, assign to it inside the function. The caller does not see the local name. Avoid using a global statement simply to get a value out. Return it explicitly.

When you find a None result where a number is expected, look at every possible path through the function. A missing return can affect only one branch. print(value) displays something and returns None. return value hands the value back and leaves the choice of display to the caller. This distinction also matters when a function helps build a report file.

Practise a Paper 2 change request

A venue charges £4 per adult and £2 per child. Bookings with at least one ticket have a £3 fee. Modify the program above so it has a function booking_total(adults, children) returning the total. Read the two counts in the caller and print exactly one integer. Use cases with no tickets, adults only, children only and a mixture. Before running, predict the outcome for three adults and two children. In the sandbox, use one count per line and Run with my input to check this separate brief.

When checking a changed function, call it twice with different inputs. This helps catch a fixed answer or an unintended dependence on a previous call.

Check your guided practice

The mixed test gives 3 * 4 + 2 * 2 + 3 = 19. Return zero when adults + children == 0. Otherwise return the total including the fee. With inputs 2 and 0 the result is 11; with 0 and 3 it is 9. Calling the function directly with these argument pairs lets you test the calculation without typing inputs into the rest of the program. If you see None, trace the paths and find which branch does not return a value.

02 · Run and repair

Return the delivery charge

This program should print one total. For £12 the expected result is 15, including a £3 charge. Repair the function so the caller can use its result.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Replace print(3) inside delivery with return 3. Keep the caller's print.

03 · Build independently

Calculate a visit cost

Write a function visit_cost(people, member) that returns the total in pounds. Then write the caller that reads the inputs and prints the returned value.

  • The first line is a non-negative integer. The second is Y for a member or N for a non-member.
  • Members pay £3 per person. Non-members pay £5 per person. Add a £2 booking fee only when at least one person visits.
  • Return the number from the function. The caller prints only the integer. After testing the output, inspect your code for the function and its return.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Handle zero people first. Use the member parameter to select the price and return the product plus the fee.

04 · Explain and transfer

Explain your reasoning

How could a second interface reuse visit_cost without changing the function?

Compare your explanation

It can obtain the people and member values in its own way, call the same function, and choose how to display the returned integer. The function has no dependence on input() or print().

Independent follow-up. Add a separate valid_group function that accepts group sizes 1 to 20. Write tests at 0, 1, 20 and 21 before connecting it to the caller.

Original GCSE practice · Pearson Edexcel 1CP2 1.1.1–1.1.2, 6.1.1, 6.1.4 and 6.6.1–6.6.3. Download your .py file to keep it after leaving the page.

Next: Test, debug and refine →