1 / 26
Programming · Grade 7 · Chapter 8

Python Functions

Building reusable, modular blocks of code with `def`, parameters, and `return`.

Chapter Goals

What We Will Master Today

The Recipe Analogy

What is a Function?

Think of a function as a saved recipe or mini-program. You give it a name once, and whenever you need to bake the cake, you call the recipe name instead of writing out every single step again!

Concept: Functions save time, prevent bugs, and make code modular and easy to read.
Language Comparison

Scratch "Make a Block" vs Python def

Scratch Custom Block

define Jump (height)
  change y by (height)
  wait 0.2 secs
  change y by (0 - height)

Python Function Syntax

def jump(height):
    y = y + height
    time.sleep(0.2)
    y = y - height

Core Concept 1

Defining and Calling Functions

# 1. FUNCTION DEFINITION (Does NOT execute until called!)
def show_welcome():
    print("======================")
    print(" Welcome to Cyber Quest!")
    print("======================")

# 2. FUNCTION CALL (Triggers execution)
show_welcome()
Execution Flow

How Python Executes Function Calls

1
Interpreter sees def (Remembers recipe name)
2
Main script calls show_welcome()
3
Jumps inside function body to run lines
4
Returns to main script line after call!
Core Concept 2

Parameters vs Arguments

Passing data INTO a function to make it flexible for different inputs.

# 'name' is the PARAMETER (variable placeholder)
def greet_player(name):
    print("Hello, player " + name + "!")

# "Alex" and "Maya" are ARGUMENTS (actual data values passed)
greet_player("Alex")
greet_player("Maya")
Multiple Inputs

Passing Multiple Parameters

def display_stats(username, level, score):
    print("User:", username)
    print("Level:", level)
    print("Score:", score)

# Order of arguments MUST match parameters!
display_stats("Ninja99", 14, 2500)
Core Concept 3

The return Statement

A function can send a calculated result back to the line of code that called it using return.

def add_numbers(a, b):
    sum_val = a + b
    return sum_val # Sends sum_val back!

# Store returned result inside a variable:
total = add_numbers(15, 25) # total becomes 40
print("Total:", total)
Critical Distinction

return vs print()

print() Function

Only displays text on screen for humans. Does NOT save data for the computer!

return Keyword

Passes data back into program memory so other lines of code can use it!

Core Concept 4

Variable Scope: Local vs Global

Local Scope

Variables created INSIDE a function. They disappear when the function finishes!

Global Scope

Variables created in the main script body outside any function. Accessible everywhere.

Spot the Mistake 1

Unbound Local Variable Trap!

def calculate_discount():
    secret_code = "SAVE20" # Local variable

calculate_discount()
print(secret_code) # Broken line outside function!

NameError: name 'secret_code' is not defined
Explanation: secret_code only exists inside calculate_discount()!
Spot the Mistake 2

Why Didn't My Code Run?

def play_sound_effect():
    print("🎵 BEEP BOOP!")

# Console Output is empty! Why?
Fix: You must CALL the function by name with parentheses: play_sound_effect()!
Smartboard Voting

What Will This Function Return for double_val(7)?

def double_val(n):
    return n * 2
    print("Done doubling!") # Note position after return

A) Returns 14, prints "Done doubling!"

B) Returns 14, NEVER prints string (return exits function!)

C) Returns 7

D) Error

Real-World Code

RPG Game Damage Calculator Function

def calc_damage(attack_power, defense_armor):
    net_damage = attack_power - defense_armor
    if net_damage < 0:
        return 0 # Armor blocked all damage
    return net_damage

player_hp = 100 - calc_damage(45, 10) # Deals 35 damage
print("Player HP remaining:", player_hp) # 65
Advanced Feature

Default Parameter Values

def create_avatar(name, role="Warrior"):
    print(name, "the", role)

create_avatar("Leo") # Uses default: "Leo the Warrior"
create_avatar("Zoe", "Mage") # Overrides default: "Zoe the Mage"
Quick Check · Quiz 1

Which Python keyword is used to define a custom function?

Afunc
Bdef
Cfunction
Ddefine
Click to reveal answer
Quick Check · Quiz 2

What is the difference between a Parameter and an Argument?

AParameters are numbers, arguments are text
BParameters are variables in definition; Arguments are values passed during function call
CThey are identical synonyms
DArguments only work inside while loops
Click to reveal answer
Quick Check · Quiz 3

What happens when a function hits a return statement?

AIt restarts from line 1
BIt immediately exits the function and sends the value back
CIt prints the value to screen
DIt deletes the script
Click to reveal answer
Quick Check · Quiz 4

Where do Local Variables created inside a function exist?

AOnly inside that specific function during execution
BEverywhere across the entire computer operating system
CInside text files automatically
DIn the web browser
Click to reveal answer
Guided Practice

Build a Geometry Helper Function

def calc_rectangle_area(length, width):
    area = length * width
    return area

room_area = calc_rectangle_area(12, 10)
print("Room Area:", room_area, "sq meters")
Best Practice

Writing Clean "Pure" Functions

A clean function takes inputs via parameters, calculates without modifying global variables, and returns an output.

Common Trap

Misconception: Parameter names must match variable names

Parameter names inside `def` are just internal labels — they do NOT need to match the variable names passed into the call!

Summary & Takeaways

What We Learned in Chapter 8

Cheat Sheet

Function Anatomy Summary

def function_name(param1, param2):
    # Function body logic
    result = param1 + param2
    return result

output = function_name(val1, val2)
Exit Ticket

Design a Function Challenge

Write a function definition for:

calc_tax(price) that returns 10% tax (price * 0.10)

Next Chapter: Prompt Engineering Basics!