Skip to content
FORGENO ADS GAMESUnlock all $8

Python Programming · Unit 5 of 8

Unit 5: Functions and classes

Functions with parameters and return values, defaults, keywords and docstrings, local and global scope, mutable arguments and the default-list trap, and classes with methods.

Opens the first lesson of this unit in Python Programming. Every lesson is open from the start.

Lesson 1: Defining functions

Goal: Define functions with parameters, return values from them, and explain the difference between return and print.

A function packages steps under a name so you can run them whenever you need them. You have been calling built-in functions since lesson one; now you will write your own. Functions let you name an idea (total_price says more than six lines of arithmetic), reuse it without copying code, and test each piece on its own. Professional Python code is mostly small functions.

def area(width, height):
    """Return the area of a rectangle."""
    return width * height

room = area(4, 3)          # 4 and 3 are the arguments
print(room, area(2.5, 2))

def starts the definition: the function's name, its parameters in parentheses and a colon, then an indented body. Parameters are the names the function uses for its inputs; arguments are the actual values you pass when you call it. Defining a function runs nothing: the body only runs when the function is called. The string on the first line of the body is a docstring, a short description of what the function does.

return sends a value back to the caller and ends the function immediately. A function with no return, or a bare return, gives back None. This is the most important distinction for new programmers: print shows something to a person and the value is then gone, while return hands a value to the code that called the function, which can store it, test it, print it or pass it on.

def add_tax_print(price):
    print(price * 1.2)

def add_tax(price):
    return price * 1.2

a = add_tax_print(10)    # shows 12.0, but a is None
b = add_tax(10)          # shows nothing, b is 12.0
print(a, b)
print(add_tax(add_tax(10)))   # returned values can be passed on

Worked example: return versus print

  1. add_tax_print(10) prints 12.0 on the screen, then returns None, so a is None.
  2. add_tax(10) prints nothing; it returns 12.0, which is stored in b.
  3. Only the returning version can be used inside other expressions, such as tax on tax.
  4. Trying add_tax_print(10) + 1 would crash: None + 1 is a TypeError.

Rule of thumb: functions compute and return; the top level of the program decides what to print.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 5 coding exercises. Graded exercise: a function that returns its result (a check makes sure it does not print).

def
The keyword that starts a function definition.
Parameter
A name in a function's definition that receives an input value.
Return value
The value a function hands back to its caller with return; None if there is no return.
Call
Running a function by writing its name followed by parentheses and arguments.
Docstring
A string on the first line of a function body that describes what it does; shown by help().

Remember: def defines; calling runs. return hands a value back and ends the function; print only shows it. No return means None.

Lesson 2: Arguments, defaults and docstrings

Goal: Use default values, keyword arguments and multiple return values, and document functions well.

Arguments can be passed in two ways. Positional arguments match parameters by order: area(4, 3). Keyword arguments name the parameter: area(height=3, width=4). Keywords make calls self-explanatory, especially with several numbers or True/False flags: send(report, urgent=True) says far more than send(report, True). Positional arguments must come before keyword ones.

A parameter can have a default value, which makes it optional: def greet(name, greeting="Hello"):. Callers can leave it out, greet("Ana"), or override it, greet("Ana", greeting="Hi"). Parameters with defaults must come after those without. Defaults are how libraries offer many options while keeping simple calls simple: sorted(items) versus sorted(items, key=len, reverse=True).

Returning several values: return low, high actually returns one tuple, which the caller unpacks: lo, hi = min_max(nums). For more than two or three values, return a dictionary or an object (later this unit) so the parts have names.

def price_label(amount, currency="EUR", decimals=2):
    """Return a price as text, such as '12.50 EUR'."""
    return f"{amount:.{decimals}f} {currency}"

def min_max(nums):
    """Return the smallest and largest number as a tuple."""
    return min(nums), max(nums)

print(price_label(12.5))
print(price_label(12.5, "GBP"))
print(price_label(1200, decimals=0, currency="JPY"))
lo, hi = min_max([4, 9, 2])
print(lo, hi)

Worked example: one function, several kinds of call

  1. With one argument, both defaults apply: 12.50 EUR.
  2. A second positional argument overrides currency: 12.50 GBP.
  3. Keywords can be given in any order: 1200 JPY. (The nested braces in the format spec use the value of decimals.)
  4. min_max returns a tuple, unpacked into lo and hi: 2 9.

Good defaults make the common call short; keywords make the unusual call readable.

A docstring explains what a function does, what it expects and what it returns, in a sentence or two. Write it before the body: if you cannot describe the function in one sentence, it probably does too much. help(price_label) shows the docstring. Optional type hints such as def area(width: float, height: float) -> float: document the expected types; Python does not enforce them, but editors and checking tools use them and many teams require them.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 5 coding exercises. Graded exercise: defaults and keyword arguments.

Positional argument
An argument matched to a parameter by its position in the call.
Keyword argument
An argument passed by naming the parameter, such as urgent=True.
Default value
A value given to a parameter in the definition, used when the caller leaves it out.
Type hint
An optional note of the expected type, such as price: float; not enforced by Python.

Remember: Defaults make arguments optional; keywords make calls readable. return a, b returns a tuple to unpack. Write the docstring first.

Lesson 3: Scope and mutability

Goal: Explain local and global scope, avoid changing shared state, and fix the mutable default argument trap.

Scope is where a name can be seen. Names assigned inside a function are local: they exist only while the function runs and cannot be seen outside. Names assigned at the top level of the file are global: functions can read them. When Python looks up a name it checks the local scope first, then the enclosing functions, then the global scope, then the built-ins (print, len...).

rate = 0.2                  # global

def with_tax(price):
    tax = price * rate      # reads the global rate; tax is local
    return price + tax

print(with_tax(10))
# print(tax)  would be a NameError: tax only existed inside the function

The trap: if a function assigns to a name anywhere in its body, that name is local for the whole function. So count += 1 inside a function, with count defined outside, raises UnboundLocalError: Python treats count as local, and the local one has no value yet. The keyword global count would make it work, but it is almost always the wrong fix, because functions that change shared state are hard to test and reason about. Pass the value in and return the new value instead: count = add_visit(count).

Mutability matters for arguments. A function receives the same object the caller has, not a copy. Rebinding a parameter (items = []) affects only the function, but changing a mutable object in place (items.append(x), items.sort()) changes the caller's object too. Sometimes that is the point, but a function that quietly changes its inputs surprises everyone. Prefer returning a new value.

def add_tag(tag, tags=[]):        # the [] is created ONCE, when def runs
    tags.append(tag)
    return tags

print(add_tag("a"))   # ['a']
print(add_tag("b"))   # ['a', 'b']  <- the same list again!

def add_tag_fixed(tag, tags=None):
    if tags is None:
        tags = []                 # a fresh list on every call
    tags.append(tag)
    return tags

print(add_tag_fixed("a"), add_tag_fixed("b"))

Worked example: the mutable default argument trap

  1. Default values are evaluated once, when def runs, not on every call.
  2. So every call that omits tags shares the one list made at definition time, and it keeps growing.
  3. The standard fix: default to None and create the list inside the function.
  4. The fixed version prints ['a'] ['b'].

This trap catches experienced developers too, and it is a favourite interview question.

Hands-on lab in the room: Predict-the-output tracer. Predict what a local assignment does to a global name, then step through it.

Hands-on lab in the room: Unit 5 coding exercises. Graded exercise: stop a function from changing the caller's list.

Scope
The part of a program where a name can be seen and used.
Local variable
A name assigned inside a function; it exists only while that call runs.
Global variable
A name assigned at the top level of a file, readable from functions.
UnboundLocalError
Raised when a function reads a local name before assigning it, often because it also assigns to that name.
Side effect
A change a function makes outside itself, such as modifying an argument or a global.
Pure function
A function whose result depends only on its arguments and which has no side effects.

Remember: Assigning inside a function makes a name local. Pass values in and return results. Never use a mutable default: use None.

Lesson 4: Classes and objects

Goal: Define a class with __init__, attributes and methods, create objects from it, and give it a readable __str__.

A class is a blueprint for a kind of object; an object (or instance) is one thing built from that blueprint. You have used objects all along: every string is an object of class str, with methods such as upper(). Writing your own classes lets you bundle data with the functions that work on it. An Account object holds a balance and knows how to deposit; a Cart holds lines and knows its total.

class Account:
    """A bank account with an owner and a balance."""

    def __init__(self, owner, balance=0):
        self.owner = owner          # attributes: data stored on this object
        self.balance = balance

    def deposit(self, amount):      # a method: a function that belongs to the class
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self.balance += amount
        return self.balance

    def __str__(self):
        return f"{self.owner}: {self.balance:.2f}"

ana = Account("Ana", 50)
ben = Account("Ben")
ana.deposit(25)
print(ana, "|", ben)

__init__ is the initialiser: Python calls it automatically when you create an object with Account("Ana", 50), and it sets up the object's attributes. Every method takes self as its first parameter: it is the particular object the method was called on, so ana.deposit(25) runs deposit with self set to ana. You never pass self yourself. Attributes are read and written with a dot: ana.balance.

Names with double underscores on both sides are special methods (often called dunder methods) that Python calls for you. __str__ decides what print() and str() show; __repr__ gives a developer-facing description, used when an object appears inside a list or in the debugger. Without them you get something like <__main__.Account object at 0x...>.

Worked example: two objects, one class

  1. Account("Ana", 50) creates an object and calls __init__ with owner "Ana" and balance 50.
  2. Account("Ben") creates a second, separate object; its balance uses the default 0.
  3. ana.deposit(25) changes only Ana's balance, to 75: each object keeps its own attributes.
  4. print(ana) calls __str__, giving Ana: 75.00.

Output: Ana: 75.00 | Ben: 0.00. A common bug is creating a list at class level instead of in __init__: then every object shares it.

Use a class when several pieces of data belong together and several functions work on them. Do not use one just to group unrelated functions. Python also offers @dataclass (from the dataclasses module) to write simple data-holding classes with less code, and inheritance (class Savings(Account):) to build a specialised class from an existing one; you will meet both at work, and the basics here are what they build on.

Hands-on lab in the room: Python playground.

Hands-on lab in the room: Unit 5 coding exercises. Graded exercise: write a Cart class (a check makes sure two carts do not share items).

Class
A blueprint that defines the attributes and methods of a kind of object.
Object (instance)
One particular thing created from a class, with its own attribute values.
Attribute
A value stored on an object, read and written with a dot: account.balance.
__init__
The special method Python calls to set up a new object's attributes.
self
The first parameter of every method: the object the method was called on.
__str__ / __repr__
Special methods that give an object's readable text and its developer-facing description.

Remember: A class bundles data (attributes set in __init__ on self) with behaviour (methods). Each object keeps its own attributes.

Practise it in Python Programming

Each lesson ends with three questions that check you can use the idea, not just recognise it. Wrong answers explain why and come back in Review. The unit ends with a 7-question quiz; pass it with 80% or more to master the unit. Hands-on lab: Unit 5 coding exercises.

Every lesson is free: no ads, no lives and no paywall.