1 / 34
Programming · Grade 10 · Chapter 9

Python: Functions

Writing code once and using it everywhere — the foundation of all serious programming.

Learning objectives

What We'll Cover

The problem

The Same 4 Lines, Three Times

A student's program calculates a discount price in three different places. They copied the same 4 lines each time. When the discount formula changes — they must fix it in three places. One forgotten spot = a bug that's very hard to find.

Better approach: Write the calculation once. Give it a name. Call it wherever needed. Fix it once when it changes.
What is a function?

Functions: Named, Reusable Blocks of Code

Define
Write the function once with def
Name
Give it a descriptive name
Call
Run it anywhere by using its name
Reuse
Call it as many times as needed
Analogy: A function is like a recipe. You write the recipe once. Then anyone can follow it — anytime, anywhere — without rewriting it.
Basic syntax

Defining and Calling a Function

# Define the function
def greet():
    print("Hello! Welcome to Python.")

# Call the function (run it)
greet()       # Hello! Welcome to Python.
greet()       # same output again
greet()       # and again
Key rule: The function body (indented block) does NOT run when defined — only when called. Definition is just registration.
Quick check · 1

What keyword is used to define a function in Python?

Afunction
Bfn
Cdef
Ddefine
Click to reveal answer
Parameters

Parameters — Making Functions Flexible

A parameter is a variable in the function definition that receives a value when the function is called.

# name is a parameter
def greet(name):
    print(f"Hello, {name}!")

# "Ahmed" and "Layla" are arguments (values passed in)
greet("Ahmed")  # Hello, Ahmed!
greet("Layla")  # Hello, Layla!
Terminology: Parameter = variable in definition. Argument = actual value passed when calling.
Multiple parameters

Functions With Multiple Parameters

def add(a, b):
    print(a + b)

add(3, 5)               # 8
add(100, 200)           # 300

def describe_student(name, grade, score):
    print(f"{name} | Grade {grade} | Score: {score}%")

describe_student("Ali", 10, 92)
Quick check · 2

What is the difference between a parameter and an argument?

AThey are the same thing
BA parameter is in the function definition; an argument is the actual value passed when calling
CArguments go inside the function body; parameters are outside
DParameters are only for print() functions
Click to reveal answer
Return values

return — Sending Back a Result

A function that just print()s cannot be used in calculations. A function that returns a value gives that value back to the caller for use.

Prints (output only)
def square(n):
  print(n * n)

result = square(5)
print(result + 1)
TypeError — result is None
✅ Returns (reusable value)
def square(n):
  return n * n

result = square(5)
print(result + 1)
Prints 26 ✓
return in action

Building with return Values

def apply_discount(price, percent):
    return price * (1 - percent / 100)

# Use the return value in expressions
sale_price = apply_discount(120, 20)
print(f"After 20% off: ${sale_price:.2f}")

# Chain functions
final = apply_discount(apply_discount(100, 10), 5)
print(f"Double discount: ${final:.2f}")
Quick check · 3

What does calling a function that uses return give you?

AThe value after return — which can be stored in a variable or used in an expression
BNothing — return only works with print()
CThe function definition
DIt stops the whole program
Click to reveal answer
Scope

Variable Scope — Local vs. Global

A variable created inside a function only exists inside that function (local scope). It cannot be accessed outside.

x = 100  # global variable

def my_function():
    y = 50  # local variable — only exists here
    print(x)  # can read global x
    print(y)  # can use local y

my_function()
print(x)         # works — x is global
print(y)         # NameError! y doesn't exist here
Scope visualised

Functions Are Isolated Rooms

Think of the global scope as a corridor, and each function as a room off that corridor.

Why this matters: Scope prevents bugs. Without it, functions could accidentally overwrite each other's variables.
Quick check · 4

What happens if you try to use a local variable outside its function?

AIt works — local variables are accessible everywhere
BNameError — the local variable doesn't exist outside the function
CThe variable becomes global automatically
DThe function runs again
Click to reveal answer
Default parameters

Default Parameter Values

A parameter can have a default value — used when no argument is provided by the caller.

def greet(name, language="English"):
    if language == "English":
        print(f"Hello, {name}!")
    elif language == "Arabic":
        print(f"مرحبا {name}!")

greet("Ahmed")               # uses default
greet("Layla", "Arabic")    # overrides default
Refactoring activity

Before and After: Refactor This Code

This code repeats the same logic three times. Refactor it into a function.

❌ Before (repeated)
p1 = 120 * (1 - 0.1)
print(f"Item 1: {p1:.2f}")
p2 = 85 * (1 - 0.1)
print(f"Item 2: {p2:.2f}")
p3 = 200 * (1 - 0.1)
print(f"Item 3: {p3:.2f}")
✅ After (function)
def discounted(price):
  return price * 0.9

print(f"Item 1: {discounted(120):.2f}")
print(f"Item 2: {discounted(85):.2f}")
print(f"Item 3: {discounted(200):.2f}")
Live coding · 1

Grade Calculator Function

Write a function that takes a numerical score and returns a letter grade.

def get_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

print(get_grade(87))  # B
Extension: Use a loop to grade a list of 5 scores.
Quick check · 5

What does this print? def double(n): return n * 2 — print(double(double(3)))

A3
B6
C12
DError
Click to reveal answer
Trace: double(3) = 6. Then double(6) = 12. Functions can be nested in calls.
Why functions?

The Three Benefits of Functions

Don't Repeat Yourself (DRY)
Write logic once. Reuse many times. Fix in one place when it changes.
Readability
A function with a good name makes complex code read like English: calculate_tax(price) is instantly clear.
Testability
Individual functions can be tested in isolation — find bugs faster and with more certainty.
Modularity
Break large programs into small, manageable pieces. Teams can work on different functions simultaneously.
Live coding · 2

Mini Shop Receipt System

Build a simple shop receipt using multiple functions.

def calculate_tax(price, rate=0.15):
    return price * rate

def calculate_total(price, rate=0.15):
    return price + calculate_tax(price, rate)

def print_receipt(item, price):
    tax = calculate_tax(price)
    total = calculate_total(price)
    print(f"{item}: ${price:.2f} + tax ${tax:.2f} = ${total:.2f}")

print_receipt("Book", 29.99)
Notice: Functions calling other functions — building layers of abstraction.
Quick check · 6

Why is it a good practice to use return instead of print() inside functions?

Aprint() is slower than return
Breturn makes the result usable in other expressions and functions; print() only outputs to screen
Cprint() causes NameErrors inside functions
DThere is no difference
Click to reveal answer
Functions in industry

Real Functions in Real Systems

Instagram
recommend_posts(user_id) — called millions of times per second with different user IDs
Google Maps
find_shortest_path(origin, destination) — wraps a complex routing algorithm in a simple interface
Banking
authorise_transaction(amount, balance, pin) — called on every purchase, returns True/False
AI Models
generate_text(prompt) — the function you call; internally runs hundreds of operations
Quick check · 7

What is the output? def add(a, b=10): return a + b — print(add(5))

AError — b is missing
B15
C5
D10
Click to reveal answer
Explanation: b has default value 10, so add(5) = 5 + 10 = 15. Default is used when the argument is not provided.
Challenge project

Build Your Own Toolkit

Create a mini Python "toolkit" file with 4 utility functions. Each must take parameters and return values.

Test each function with at least 2 different inputs. Share with the class and explain what each does.
Exit reflection

What Would Your Codebase Look Like Without Functions?

Imagine writing an entire app — a quiz, a shop, a game — with no functions at all. Just one continuous block of code, top to bottom.

Discuss: What problems would arise? How many lines long would it be? How hard would it be to fix a bug? How hard to add a new feature? This is why functions are not optional for real programs.
Before you go

Today We Learned...

Final chapter: How AI models work — and now that you know Python and functions, you can start understanding the code that makes them run.