Aral Code

Functions & Modules Lesson 18 of 23

Python Functions

Define reusable functions with def, pass arguments, return values (even several at once), use default and keyword arguments, and understand local and global scope.

A function is a named block of code that does one job. You define it once and call it whenever you need it. You've already used built-in functions like print(), len() and input(). Now you'll write your own.

Defining and calling a function

def greet():
    print("Magandang umaga po!")
    print("Handa na ba kayo?")

greet()
greet()

Output

Magandang umaga po!
Handa na ba kayo?
Magandang umaga po!
Handa na ba kayo?

def starts the definition, followed by the name, parentheses and a colon. The body is indented. Nothing happens until you call the function with greet().

Parameters and arguments

def greet(name, section):
    print(f"Hi {name} of {section}!")

greet("Ana", "Rizal")
greet("Ben", "Mabini")

Output

Hi Ana of Rizal!
Hi Ben of Mabini!

name and section are parameters; "Ana" and "Rizal" are the arguments passed in.

return: sending back a result

def average(grades):
    return sum(grades) / len(grades)

def descriptor(grade):
    if grade >= 90:
        return "Outstanding"
    if grade >= 85:
        return "Very Satisfactory"
    if grade >= 80:
        return "Satisfactory"
    if grade >= 75:
        return "Fairly Satisfactory"
    return "Did Not Meet Expectations"

avg = average([88, 91, 85])
print(f"{avg:.2f} – {descriptor(avg)}")

Output

88.00 – Very Satisfactory

return ends the function immediately and hands back a value. That's why descriptor doesn't need elif: once a return runs, the rest is skipped.

Returning several values

def stats(grades):
    return min(grades), max(grades), sum(grades) / len(grades)

low, high, avg = stats([88, 72, 95, 81])
print(f"Lowest {low}, highest {high}, average {avg}")

Output

Lowest 72, highest 95, average 84.0

Python packs the values into a tuple, and you unpack them into variables.

Default values

def fare(km, discount=False):
    amount = 13 + max(0, km - 4) * 1.80
    if discount:
        amount *= 0.80      # 20% student/senior discount
    return round(amount, 2)

print(fare(9))
print(fare(9, True))

Output

22.0
17.6

Keyword arguments

You can name arguments when calling, which makes calls clearer and lets you change the order:

print(fare(km=9, discount=True))
print(fare(discount=True, km=12))

Output

17.6
21.92

Scope: local and global

Variables created inside a function are local: they exist only inside it.

def compute():
    total = 100
    return total

compute()
print(total)

Error

NameError: name 'total' is not defined

This is good: functions can't accidentally mess up each other's variables. Pass data in with parameters and get results out with return. Avoid the global keyword except in very small scripts.

Docstrings

Describe what a function does with a triple-quoted string as its first line:

def bmi(weight_kg, height_m):
    """Return the Body Mass Index, rounded to 1 decimal."""
    return round(weight_kg / height_m ** 2, 1)

print(bmi(50, 1.6))
help(bmi)

Output

19.5
Help on function bmi in module __main__:

bmi(weight_kg, height_m)
    Return the Body Mass Index, rounded to 1 decimal.

Lambda functions

A lambda is a tiny unnamed function written on one line. It's mostly used with sorted, max and similar:

double = lambda n: n * 2
print(double(21))

products = [("Kape", 8), ("Pandesal", 25), ("Itlog", 9)]
print(max(products, key=lambda p: p[1]))

Output

42
('Pandesal', 25)

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which keyword defines a function in Python?
2. What does a function return if it has no return statement?
3. Given def f(x, y=10): return x + y, what is f(5)?
4. What's the difference between print and return?

By Sir Reyel · Last updated 2026-12-04