Functions Reusing Code Slides
COMPUTING FOUNDATIONS • PYTHON DAY 1
Lesson Duration: 45 min
Functions: Reusing Code
Giving a Name to a Piece of Code
Today's Learning Targets
01 I can explain why programmers use functions.
02 I can define and call a simple Python function.
03 I can identify the difference between creating and running a function.
Foundation Review
02 / 21
Start with something you already use every day:
player_score = 0
What does this variable do?
It gives the value 0 a name so we can store it and use it later.
name = "Alex"
💡 Variables let us give names to pieces of DATA.
You give data a label so you don't have to keep retyping raw values.
The Big Leap
03 / 21
What if we want to reuse CODE?
What if, instead of reusing a single value, we want to reuse a whole set of instructions?
VARIABLE
Gives a name to...
DATA
score = 10 • name = "Jordan"
New Concept
FUNCTION
Gives a name to...
CODE
def coin_flip(): ...
Definition: A function is a named block of code that can be reused whenever you need it.
Familiar Code
04 / 21
Bring Back the Coin Flip
Remember this program we built using random.choice()?
import random
result = random.choice(["heads", "tails"])
print(f"The coin landed on {result}.")
Question for You:
What if we wanted to flip a coin 5 different times throughout a big game?
Copying and pasting this code over and over works, but it gets messy, long, and hard to fix!
Instead of copying lines of code, let's give those instructions a name!
Syntax Breakdown
05 / 21
Give the Code a Name: def
def coin_flip():
result = random.choice(["heads", "tails"])
print(f"The coin landed on {result}.")
def
Short for "define". Tells Python we are building a new function.
coin_flip
The name we choose for our reusable block of code.
():
Parentheses signal a function; the colon begins the block.
Indent
Shows Python which instructions belong inside the function.
Syntax Rule: Header line has def, name, (), and :. Body lines must be indented.
Crucial Concept
06 / 21
COMMON MISCONCEPTION
Define does NOT mean run!
def coin_flip():
result = random.choice(...)
print(...)
What happens if you run only this cell in Python?
Console Output:
(Nothing is printed! Empty screen!)
Python stored the instructions, but we haven't told Python to execute them yet.
Golden Rule:
Defining a function creates it.
Calling a function runs it.
Teaching Python a recipe doesn't bake the cake until you say "bake it!"
Action Time
07 / 21
Calling the Function
To run the stored instructions, write the function name followed by parentheses:
coin_flip() ← Function Call
This tells Python: "Jump to coin_flip, run every indented instruction, then come right back."
What happens here?
coin_flip()
coin_flip()
coin_flip()
🎉 3 independent coin flips!
We wrote the actual logic once, but we reused it 3 times with 3 quick lines!
Notice: The function call does NOT use the keyword def.
Side-by-Side Comparison
08 / 21
Why Is This Better Than Copy & Paste?
❌ WITHOUT FUNCTION Repetitive & bulky
result = random.choice(["heads", "tails"])
print(result)
# Repeated 2 more times...
result = random.choice(["heads", "tails"])
print(result)
If you want to edit the message, you must change every copy!
✅ WITH FUNCTION Clean & reusable
coin_flip()
coin_flip()
coin_flip()
Easier to read: Clear intent at a glance
Easier to change: Update logic in ONE place
Fewer bugs: No copy-paste typo accidents
Programmers call this core principle: DRY (Don't Repeat Yourself)
Live Code Along
09 / 21
OPEN GOOGLE COLAB
Let's Build It Together
1 Type & Run This Cell:
import random
def coin_flip():
result = random.choice(["heads", "tails"])
print(f"The coin landed on {result}.")
❓ Did the coin flip? No! Only defined!
2 Now Call It Below:
# At the bottom of your cell:
coin_flip()
🎯 Run again: Now you see:
"The coin landed on heads."
Try adding coin_flip() two more times to watch it flip again!
Core Concept Anchor
10 / 21
Define vs. Call
Keep these two distinct actions crystal clear in your mind:
DEFINE
def coin_flip():
Teach Python what to do.
• Creates and names the instruction block.
• Runs ZERO instructions right now.
• Uses the keyword def and a colon :.
CALL
coin_flip()
Tell Python to do it!
• Executes the stored instructions.
• Can be called as many times as you like.
• Uses the function name with ().
Define = Teach Python the recipe | Call = Tell Python to cook!
Python Rules
11 / 21
Indentation Still Matters!
Just like with if statements and loops, Python demands indentation.
What is wrong here?
def coin_flip():
result = random.choice(...)
print(result)
⚠️ IndentationError: expected an indented block after function definition!
Indented Correctly
def coin_flip():
result = random.choice(...)
print(result)
✅ Indenting 4 spaces tells Python: "These lines are the inside body of this function."
Any line not indented is considered outside the function!
Flow of Execution
12 / 21
Functions and Sequence
Calling a function does not break sequence; Python pauses, runs the function, and comes right back!
Trace this code from top to bottom:
print("Welcome!")
coin_flip()
print("Game over!")
Execution Flow:
1 print("Welcome!") prints first
2 Jumps into coin_flip() and runs its lines
3 Returns back and prints "Game over!"
Python always remembers where it was before entering the function!
Connecting Old & New
13 / 21
Functions can contain everything we already know!
Functions are not a replacement for sequence, conditionals, or loops.
They are a way to ORGANIZE and REUSE code that contains those structures!
Conditionals inside a function:
def coin_flip():
result = random.choice(["heads", "tails"])
if result == "heads":
print("Heads! You win!")
else:
print("Tails! Try again!")
You can put loops, calculations, user inputs, and conditionals inside any function!
Real Application: Rock, Paper, Scissors
14 / 21
Reuse in Another Game!
In your Rock, Paper, Scissors game, what happens on a tie?
Your previous tie check:
if player == computer:
print("It's a tie!")
A tie just ends the round. Can we make it exciting?
Reusing coin_flip as a tiebreaker!
if player == computer:
print("It's a tie! Coin flip!")
coin_flip()
🚀 We took code we wrote earlier and plugged it straight into a brand new game with one single line!
This is why programmers build functions: modular code blocks that plug into anything.
Looking Ahead
15 / 21
MYSTERY FOR NEXT LESSON
The Problem We Haven't Solved Yet
The coin_flip() function prints to the screen...
...but how does the Rock, Paper, Scissors program know who won the tiebreaker?
How could the function send the result back to the main program so we can award a point to player_score?
Coming in Lesson 2: return
For today: Master defining and calling simple action functions!
Hands-On Practice (3 Minutes)
16 / 21
Pick ONE to Build in Colab
Practice the steps: def → name → (): → indent body → call it!
Option A
welcome()
Prints a welcome banner message for your game.
def welcome():
print("Welcome!")
Option B
goodbye()
Prints a friendly exit message when a player leaves.
def goodbye():
print("Thanks!")
Option C
show_score()
Prints a scoreboard header or round summary.
def show_score():
print("Score: 0")
Remember: Type the definition, then call it on a new line without indentation!
Code Tracing Challenge
17 / 21
Predict the Output!
What will print to the screen, and in what exact order?
def message():
print("Hello!")
print("Start")
message()
message()
print("End")
Expected Console Output:
Start
Hello!
Hello!
End
Notice: Hello! does not print until message() is explicitly called!
Trace line by line: define → skip body until called → run main sequence!
Debugging Challenge #1
18 / 21
SPOT THE BUG
Why doesn't this run?
def cheer():
print("You can do it!")
cheer
The Explanation:
Writing just cheer only mentions the function's name—it doesn't call it!
The parentheses () are the action trigger that tells Python: "Run this right now!"
Correct Call: cheer()
Never forget the parentheses () when calling a function!
Debugging Challenge #2
19 / 21
SPOT THE BUG
What is missing here?
def cheer()
print("You can do it!")
Missing Colon & Indent Check!
The definition header must end with a : (colon).
Fixed Code:
def cheer():
print("You can do it!")
The colon tells Python: "Get ready, an indented code block is starting right now."
Header checklist: def + name + () + :
Big Picture Synthesis
20 / 21
Our Complete Programming Toolbox
Look at how much real programming power you now control:
1
Variables
Store Data
Name and remember pieces of data for later.
x = 10
2
Conditionals
Make Decisions
Branching paths: Selection
if / else
3
Loops
Repeat Code
Automated cycles: Iteration
for / while
4
Functions
Reuse Code
Name and organize whole sets of instructions.
def name():
Functions don't replace Sequence, Selection, or Iteration—they organize them into clean, reusable modules!
Exit Ticket (Last 5 Minutes)
21 / 21
Show What You Know
1. Definition
What is a Python function in your own words?
2. Why Use Functions?
Why use a function instead of copying and pasting code?
3. Keyword
What keyword begins a Python function definition?
4. Define vs. Call
What is the difference between defining and calling a function?
5. Which Runs It?
coin_flip vs. coin_flip()
6. Application
Why is coin_flip() useful inside Rock, Paper, Scissors?
7. Next Step: What problem do we still need to solve if RPS needs to know whether the coin was heads or tails?
Submit your responses before packing up your laptop! Great work today!
Reusing Code Worksheet
Computing Foundations • Python Unit
Functions: Reusing Code
Name:
Date:
Period:
Targets: Explain why functions exist • Define & call a function with def • Distinguish creating vs. running code
1
Variables vs. Functions: The Core Connection
VARIABLE e.g. score = 0
A variable gives a name to a piece of:
Purpose: Store and retrieve a value later.
FUNCTION e.g. def coin_flip():
A function gives a name to a piece of:
Purpose: Store and reuse a set of instructions.
2
Anatomy of a Function Definition
def coin_flip():
result = random.choice(["heads", "tails"])
print(f"The coin landed on {result}.")
def Keyword Purpose:
() Parentheses Purpose:
: Colon Purpose:
Indentation Why it is required:
3
Deep Dive: Define vs. Call
1. DEFINING A FUNCTION Storage
What does defining do to Python's memory?
Does Python execute any code right now? ( Circle one: YES / NO )
2. CALLING A FUNCTION Execution
What does calling instruct Python to do?
Write the exact syntax to call coin_flip:
Lab Checkpoint: In Google Colab, you type the definition cell and press RUN. Why does nothing print out?
Computing Foundations • Functions Day 1 Page 1 of 2
Student Worksheet • Reusing Code in Action
Name: ______________________
4
Code Tracing & Flow of Sequence
Python Code:
def message():
print("Hello!")
print("Start")
message()
message()
print("End")
Predict the Console Output:
Write the printed lines in the exact order they appear:
Hint: Remember that sequence still flows top-to-bottom!
5
Bug Buster: Spot & Fix the Common Mistakes
Bug #1 No Action Taken
def cheer():
print("Go team!")
cheer
Why does the function fail to run?
Write the corrected call line:
Bug #2 SyntaxError
def cheer()
print("Go team!")
What specific punctuation mark is missing?
Write the corrected header line:
6
Game Integration: Rock, Paper, Scissors Tiebreaker
In your Rock, Paper, Scissors game, tie rounds just end. Below, add our reusable coin_flip() function inside the conditional block so ties trigger an immediate coin flip!
if player == computer:
print("It's a tie! Let's flip a coin for the win.")
# Write your function call here:
7
Exit Ticket & The Next Mystery
1. Why use a function instead of copy/paste?
Give at least one practical reason (e.g. DRY principle):
2. The Unsolved Mystery:
coin_flip() prints to the screen, but how can we send the result back to RPS to award a point? What keyword will we learn next?
Computing Foundations • Functions Day 1 Page 2 of 2