Home › Theme B › B2 › B2.3 › B2.3.4

B2.3.4 Functions and modular programs

SL + HLCommand term: Construct

1. Inside a function call: the call stack

One function calls two others. Watch each call push a new frame holding its parameters and local variables, and each return pop it off and hand back a value.

2. Function machine: same code, different inputs

A function is a reusable machine: arguments go in, a value comes out. Try different arguments. Then compare a function that returns with one that only prints.

Function:
Printed: -   Returned: -
Java signature:

3. Maintenance challenge: copy-paste vs a function

The library changes its fine from 0.5 to 0.75 per day. Click every place that must change in each version (yellow), then run both. Which version is easier and safer to maintain?

Copy-and-paste version

Edits made: 0

Modular version

Edits made: 0
Expected after the change: Ana 4.5, Ben 3.0, Chen 12.0.

4. Design the modules

Split ShelfWise into three modules, each with one clear responsibility. Assign each function, check, and see the import statements main.py would need.

5. Flip-card deck

Click to flip. Say the answer before you flip.

6. Predict the output

Trace each call. Streaks of 3+ score double.

Round 0/10Score 0Streak 0Best 0
Press start!

7. Which benefit of modularization?

Each scenario shows one main benefit of splitting code into functions and modules.

Round 0/10Score 0Streak 0Best 0
Press start!

8. 45-second speed round: what is returned?

A new function and call each time.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 3, task 4. One long file is hard to read, test and share. Split ShelfWise into three modules in the same folder: catalogue.py (books), loans.py (borrowing rules) and main.py (the program). Every function takes what it needs as parameters and gives back a return value: no global variables.
View: catalogue.pyloans.pymain.py

Expected output (run main.py)

True False ['Dune', 1] [['Ana', 'Dune']] 3.0 1.5 0.0

Think about it

(1) Why does lend take catalogue and loans as parameters instead of using global variables? (2) What does if __name__ == "__main__": allow another module to do? (3) Which module would change if the library introduced a new fine rule, and which would not?

Check my modules

    Sprint 3 complete. Next sprint (B2.4): ShelfWise searches and sorts its catalogue efficiently, measured with Big O.

    Practical tasks

    Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    Task 1: A conversion table with functions

    Write c_to_f(c) and f_to_c(f), then table(start, stop, step) that uses c_to_f to print a neatly aligned Celsius-to-Fahrenheit table.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_4_average.py
    def c_to_f(c):
        pass  # your code here
    
    def f_to_c(f):
        pass  # your code here
    
    def table(start, stop, step):
        pass  # your code here
    
    # ---- tests ----
    table(-10, 40, 10)
    print(round(f_to_c(98.6), 1))
    

    Expected output when your code is correct:

        C      F
      -10   14.0
        0   32.0
       10   50.0
       20   68.0
       30   86.0
       40  104.0
    37.0
    Hint
    Use f-string widths, like {x:>6.1f}, to line up columns.
    Model solution
    File: b2_3_4_average_solution.py
    def c_to_f(c):
        return c * 9 / 5 + 32
    
    def f_to_c(f):
        return (f - 32) * 5 / 9
    
    def table(start, stop, step):
        print(f"{'C':>5} {'F':>6}")
        for c in range(start, stop + 1, step):
            print(f"{c:>5} {c_to_f(c):>6.1f}")
    
    # ---- tests ----
    table(-10, 40, 10)
    print(round(f_to_c(98.6), 1))
    
    Moderate

    Task 2: A modular report card

    Break this problem into small functions: mean(marks), letter(avg) (A for 80+, B for 65+, C for 50+, otherwise D) and report(name, marks) that returns one line like "Ana: mean 81.3 grade A". report must call the other two.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_4_moderate.py
    def mean(marks):
        pass  # your code here
    
    def letter(avg):
        pass  # your code here
    
    def report(name, marks):
        pass  # your code here
    
    # ---- tests ----
    for name, marks in [("Ana", [78, 85, 81]), ("Ben", [60, 70, 66]), ("Cai", [40, 52, 49])]:
        print(report(name, marks))
    

    Expected output when your code is correct:

    Ana: mean 81.3 grade A
    Ben: mean 65.3 grade B
    Cai: mean 47.0 grade D
    Hint
    Each function does one job and returns a value; only the top level prints.
    Model solution
    File: b2_3_4_moderate_solution.py
    def mean(marks):
        return sum(marks) / len(marks)
    
    def letter(avg):
        if avg >= 80:
            return "A"
        elif avg >= 65:
            return "B"
        elif avg >= 50:
            return "C"
        return "D"
    
    def report(name, marks):
        avg = mean(marks)
        return f"{name}: mean {avg:.1f} grade {letter(avg)}"
    
    # ---- tests ----
    for name, marks in [("Ana", [78, 85, 81]), ("Ben", [60, 70, 66]), ("Cai", [40, 52, 49])]:
        print(report(name, marks))
    
    Challenging

    Task 3: Validate a student record

    A record is a dictionary such as {"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}. Write separate helper functions valid_id (S followed by 4 digits), valid_name (at least two words, letters and spaces only), valid_year (11 or 12), valid_email (exactly one @ and a dot after it), and validate(record) that returns a list of the names of fields that fail. Missing fields also fail.

    Starter file (write your code where it says pass # your code here):

    File: b2_3_4_challenging.py
    def valid_id(v):
        pass  # your code here
    
    def valid_name(v):
        pass  # your code here
    
    def valid_year(v):
        pass  # your code here
    
    def valid_email(v):
        pass  # your code here
    
    def validate(record):
        pass  # your code here
    
    # ---- tests ----
    print(validate({"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}))
    print(validate({"id": "s42", "name": "Ana", "year": 13, "email": "ana@school"}))
    print(validate({"name": "Ben Wu 2", "year": 11}))
    

    Expected output when your code is correct:

    []
    ['id', 'name', 'year', 'email']
    ['id', 'name', 'email']
    Hint
    Store the checking functions in a dictionary: functions are values too.
    Model solution
    File: b2_3_4_challenging_solution.py
    def valid_id(v):
        return isinstance(v, str) and len(v) == 5 and v[0] == "S" and v[1:].isdigit()
    
    def valid_name(v):
        return isinstance(v, str) and len(v.split()) >= 2 and all(w.isalpha() for w in v.split())
    
    def valid_year(v):
        return v in (11, 12)
    
    def valid_email(v):
        if not isinstance(v, str) or v.count("@") != 1:
            return False
        return "." in v.split("@")[1]
    
    def validate(record):
        checks = {"id": valid_id, "name": valid_name, "year": valid_year, "email": valid_email}
        return [field for field, check in checks.items() if field not in record or not check(record[field])]
    
    # ---- tests ----
    print(validate({"id": "S0042", "name": "Ana Li", "year": 12, "email": "ana@school.cn"}))
    print(validate({"id": "s42", "name": "Ana", "year": 13, "email": "ana@school"}))
    print(validate({"name": "Ben Wu 2", "year": 11}))
    

    Learning objectives

    By the end of this page you should be able to:

    1. Construct functions with parameters and return values, and call them with different arguments to reuse the same code.
    2. Distinguish between parameters and arguments, and between returning a value and printing it, and trace function calls using the call stack.
    3. Explain the principles of scope (local versus global) and why functions should communicate through parameters and return values.
    4. Construct a modular program split into functions and modules, each with a single clear responsibility, using import.
    5. Explain the benefits of modularization (reuse, maintainability, testing, readability and teamwork) in given scenarios.

    Functions

    def calculate_fine(days_held, is_teacher=False):     # definition: parameters
        """Return the fine for a book kept days_held days."""
        late = days_held - 14                            # local variable
        fine = late * 0.5 if late > 0 else 0.0
        if is_teacher:
            fine = fine / 2
        return fine                                      # output
    
    f = calculate_fine(20)                # call with an argument: f = 3.0
    t = calculate_fine(20, True)          # same code, different inputs: 1.5
    • A function is a named, reusable block of code that performs one task. It runs only when it is called.
    • Parameters are the variables in the definition (days_held); arguments are the actual values passed in a call (20). A default parameter (is_teacher=False) may be left out.
    • return sends a value back to the caller and ends the function. A function with no return gives back None. Printing is not returning: a printed value cannot be stored or used in a calculation.
    • In Java a function is a method with declared types: static double calculateFine(int daysHeld, boolean isTeacher) { ... }; void means no return value.
    • Each call gets its own frame on the call stack (B2.2.3), holding its parameters and locals; the frame is removed when the function returns.

    Scope principles

    • Local variables (including parameters) exist only inside their function, during the call. Two functions can both use a variable called total without interfering.
    • Global variables are visible everywhere, but a function that changes them (with global) is harder to understand, test and reuse, because its behaviour depends on hidden state.
    • Good practice: pass data in as parameters and send results out with return. Keep globals for constants such as LOAN_DAYS = 14.

    Modularization

    Modularization divides a program into separate, self-contained parts: functions, and modules (separate files) that group related functions. It is decomposition (B1.1.2) applied to code.

    # main.py
    from catalogue import find_book, available
    from loans import calculate_fine, lend
    
    def main():
        ...
    
    if __name__ == "__main__":    # run main() only when this file is run directly,
        main()                    # not when another module imports it

    Java organises code into classes and packages in the same spirit (B3).

    Benefits

    BenefitWhyShelfWise example
    ReuseWrite once, call many times, even from other programscalculate_fine is used by the desk, the reports and the reminder emails
    MaintainabilityA change is made in one placeA new fine rate means editing one function, not ten copies
    Testing and debuggingEach function can be tested on its own; bugs are isolatedTest calculate_fine with boundary data before connecting the menu
    ReadabilityNamed functions describe what happens; the main program reads like a planif available(books, title): lend(...)
    TeamworkDifferent people can build different modules at the same timeOne student writes loans.py while another writes the user interface

    Designing good functions

    • One job per function, with a descriptive verb name (calculate_fine, not f2).
    • Short enough to read on one screen; a docstring describing inputs and output.
    • Avoid side effects such as printing or changing globals, unless that is the function's job.

    Use the 中文 button at the top to show or hide the Chinese terms.

    Term中文Meaning

    Choose an answer. You get instant feedback.

    Score: 0 /

    Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.

    1. Distinguish between a parameter and an argument. [2]

    A parameter is a variable named in the function definition that receives a value [1]; an argument is the actual value passed to the function when it is called [1].

    2. Explain two benefits of modularization for the team developing ShelfWise. [4]

    Award [1] for a benefit and [1] for its explanation in context, twice: reuse, e.g. one calculate_fine used by the desk and the report module; maintainability, e.g. a rate change is made in one place; testing, e.g. each module tested independently so errors are isolated; teamwork, e.g. different members develop catalogue.py and loans.py in parallel; readability.

    3. State the output. [3]

    def double(n):
        n = n * 2
        return n
    
    x = 5
    y = double(x)
    print(x, y, double(double(1)))
    x is unchanged, 5, because n is a local copy [1]; y = 10 [1]; double(double(1)) = double(2) = 4 [1]. Output: 5 10 4.

    4. Construct a Python function average(values) that returns the mean of a list of numbers, or 0 if the list is empty. [4]

    Function header with one parameter [1]; handle the empty list, e.g. if len(values) == 0: return 0 [1]; total the values with a loop (or sum) [1]; return total / len(values) [1].

    5. Explain why functions should use parameters and return values rather than global variables. [3]

    A function that depends on or changes globals has hidden inputs/outputs, so its behaviour is harder to predict [1]; it cannot easily be reused in another program or tested on its own [1]; with parameters and return values the function is self-contained and other code cannot accidentally change its data / name clashes are avoided [1].

    6. Outline the difference between a function that returns a value and one that prints it. [2]

    Returning passes the value back to the calling code, where it can be stored or used in further processing [1]; printing only displays it to the user, and the function itself returns None [1].