Returning Values Slides
Computing Foundations • Unit 4: Modular Python
Functions Day 2: Returning Values
Making Our Coin Flip Work Inside Rock, Paper, Scissors
Today's Learning Targets
1 I can explain what return does in a function.
2 I can store a value returned by a function in a variable.
3 I can use a returned value to make another part of a program do something.
4 I can test and debug a program to ensure it behaves correctly.
Quick Review: Defining Functions
Warm-Up Check
Function Code
def coin_flip():
result = random.choice([
"heads", "tails"
])
print(f"Coin: {result}")
To Call It Later: coin_flip()
Think & Answer
1. Name? coin_flip
2. Indented lines? The indented lines belong to the function body.
3. Does defining run it? NO! Defining teaches Python the steps.
4. How do we execute it? coin_flip()
Key Rule: A function sits waiting quietly until your program calls its name!
The Problem in Rock, Paper, Scissors
Tiebreaker Dilemma
Your Current RPS Tie Code
if player == computer:
print("It's a tie!")
coin_flip()
# Now who gets the point?!
The coin flipped and printed to the terminal... but what happened next?
The Big Question:
How does the Rock, Paper, Scissors program KNOW what the coin landed on?
Printing lets the HUMAN sitting at the keyboard see the text.
But the PROGRAM still needs access to that data if it wants to award a score point!
The Missing Link We Need: return
Without returning data, functions are one-way dead ends for your program logic!
Core Distinction: print() vs return
Golden Concept
print() For the HUMAN
def coin_flip():
coins = ["heads", "tails"]
result = random.choice(coins)
print(result)
Displays text on the terminal screen. Once displayed, the data is gone. The rest of your Python code cannot inspect or use it.
🗣️ Gives information to the HUMAN.
return For the PROGRAM
def coin_flip():
coins = ["heads", "tails"]
result = random.choice(coins)
return result
Sends the result back to whoever called the function. The caller catches it in a variable and makes decisions or updates scores with it!
🔄 Gives information back to the PROGRAM.
Remember: You cannot use print() in an if check, but you CAN check a returned value!
Where Does the Returned Value Go?
Catching the Value
The Golden Syntax
tiebreaker = coin_flip()
1
Python runs the coin_flip() function.
2
The function chooses "heads" or "tails".
3
return launches that value back out.
4
The variable tiebreaker catches and stores it!
Think of substitution: If return "heads" happens... → tiebreaker = "heads"
The variable on the left of = receives whatever value is returned on the right!
Trace the Function: Follow the Flow
Step-by-Step Execution
Program Code
def coin_flip():
result = random.choice([
"heads", "tails"
])
return result
tiebreaker = coin_flip()
print(tiebreaker)
1 Python reaches tiebreaker = coin_flip()
2 Execution jumps up into the coin_flip() body
3 A random choice is selected and stored in result
4 return launches that string value back down
5 The value lands in tiebreaker
6 Python continues smoothly to the next instruction
Flow: Caller → Function Body → Return Value → Stored in Variable → Next Line
Quick Check: Predict the Result
Concept Check
Study This Code
def double(number):
result = number * 2
return result
answer = double(4)
What value will be stored in answer?
8
Why? The function computes 4 * 2 = 8.
The keyword return passes 8 back out, where answer = catches it!
Key Takeaway: Any value sent out by return can be captured in a variable.
Back to the Coin Flip
What Comes Back?
Our Updated Function
def coin_flip():
result = random.choice(["heads", "tails"])
return result
tiebreaker = coin_flip()
What are the two possible values stored in tiebreaker?
🪙 "heads"
🪙 "tails"
Because tiebreaker holds one of these exact strings, we can test it with conditionals!
Next step: Using an if / else block to decide what to do!
Use the Returned Value: Dividing Responsibilities
Selection Structure
Checking the Returned Variable
if tiebreaker == "heads":
print("Heads! You win the tiebreaker!")
player_score += 1
else:
print("Tails! Computer wins the tiebreaker!")
computer_score += 1
The program uses the data to update game state (score += 1)!
Job 1: The Function
Flip the coin
It doesn't care about scores or RPS rules. It just flips and returns.
Job 2: The Main Program
Decide what it means
The main game logic decides who gets the point and prints the announcements.
🌟 Separation of Concerns: Building small, specialized tools makes programs easier to read and debug!
The function produces the data; the main program decides what action to take.
Put It Inside RPS: The Complete Tie Section
Integration
Updated Tie Condition
if player == computer:
print("It's a tie! Time for a coin flip.")
tiebreaker = coin_flip()
if tiebreaker == "heads":
print("Heads! You win the tiebreaker!")
player_score += 1
else:
print("Tails! Computer wins the tiebreaker!")
computer_score += 1
Don't Start Over!
You are NOT rewriting your program.
You are adding a reusable function tool to your existing code.
Call coin flip
Catch returned string
Award tiebreaker point
Notice how clean and readable the tiebreaker logic becomes!
Identify the Concepts
Code Anatomy
Can You Spot Each Element?
def coin_flip(): ← [1]
result = random.choice([...])
return result ← [2]
while player_score < 3: ← [3]
# [Sequence of player input & choices]
if player == computer: ← [4]
tiebreaker = coin_flip() ← [5] & [6]
All major computer science pillars work together in this single snippet!
Concept Match
[1] Function Definition def coin_flip():
[2] Returned Value return result
[3] Iteration (Loop) while score < 3:
[4] Selection (Branch) if player == computer:
[5] Function Call coin_flip()
[6] Variable Storage tiebreaker = ...
Everything connects: Sequence, Selection, Iteration, and Modular Functions!
Teacher Code-Along: 5 Steps to Upgrade
Open Your IDE
1
Import Check
Ensure import random is at line 1.
import random
2
Define Function
Add coin_flip() near the top with return.
def coin_flip():
3
Find Tie Branch
Locate if player == computer:.
if player == comp:
4
Call & Catch
Assign call to variable tiebreaker.
tie = coin_flip()
5
Award Point
Write if/else to add 1 to the winner.
score += 1
⚠️ Golden Habit: Run your code after EACH change to catch syntax bugs immediately!
Student Challenge: Required Upgrade
20 Minutes Dedicated Build
Your Program Must Satisfy All Criteria:
✓ Uses a while loop until someone reaches 3 points
✓ Includes a defined coin_flip() function
✓ Calls coin_flip() ONLY when RPS ends in a tie
✓ Function returns "heads" or "tails"
✓ Stores the returned result in a variable
✓ Uses that variable to award the tiebreaker point
✓ Displays the final game winner when someone reaches 3 points!
Coder Honor Code
Modify your own existing RPS program!
Do not copy/paste a brand new program. The best learning happens when you adapt your own logic.
Need help? Trace the function on paper first!
Once finished, move immediately to the Testing Table on the next slide!
Test Your Program: 5 Deliberate Tests
Quality Assurance
Test 1
Player Wins
Play a normal round where you win (e.g., Rock vs Scissors).
Does player_score increase by 1?
Test 2
Computer Wins
Play a normal round where computer wins.
Does computer_score increase by 1?
Test 3
RPS Ties
Both choose Rock (or repeat until tie).
Does coin_flip() trigger?
Test 4
Coin Point
Observe tiebreaker outcome closely.
Does EXACTLY one score increase?
Test 5
Game Over
Play until someone hits 3 points.
Does while loop cleanly stop?
Do not guess whether your code works — prove it with tests!
Recording Your Test Results
Verification Log
| Test Scenario |
Worked First Try? |
What Did You Fix? (or notes) |
| 1. Player wins normal round |
[ Yes / No ] |
Score incremented properly |
| 2. Computer wins normal round |
[ Yes / No ] |
Computer score incremented |
| 3. Tie triggers coin flip |
[ Yes / No ] |
Checked if/elif branch |
| 4. Coin flip awards point |
[ Yes / No ] |
Verified return value caught |
| 5. Game stops at 3 points |
[ Yes / No ] |
Loop condition checked |
💡 Pro Tip: Testing isn't just checking if the code runs without an error red box. Testing means checking if the program behaves the way it is supposed to!
Debugging Challenge 1: The Ghost Value
Spot the Flaw
Broken Code
def coin_flip():
coins = ["heads", "tails"]
result = random.choice(coins)
print(result)
tiebreaker = coin_flip()
if tiebreaker == "heads":
player_score += 1
Why doesn't the player ever receive a point when it lands on heads?
Diagnosis & Solution
Diagnosis: The function prints to the screen, but never returns anything! In Python, tiebreaker ends up holding None!
Fix: Replace print(result) with:
return result
Now tiebreaker actually receives the string value "heads"!
Without return, a function sends back None by default!
Debugging Challenge 2: Indentation Trouble
Syntax Sleuth
What's Wrong Here?
def coin_flip():
result = random.choice(
["heads", "tails"]
)
return result
Python Error: IndentationError: expected an indented block
The Correct Version
def coin_flip():
result = random.choice(
["heads", "tails"]
)
return result
Rule: Everything inside a function must be indented 4 spaces (or 1 tab)!
Indentation tells Python: "These lines belong inside this function container!"
Optional Extension 1: Polish the Output
Level Up UX
Readable F-Strings
tiebreaker = coin_flip()
print(f"🪙 The coin landed on {tiebreaker.upper()}!")
Add Dramatic Suspense
Print a suspenseful countdown or ASCII art banner before announcing the coin flip result!
Display Scoreboard
Print a clean formatted score summary after the tiebreaker finishes so the user knows where they stand.
Great software developers think about both clean code and user experience!
Optional Extension 2: Let Player Call the Coin
Next Lesson Preview
Player Calls Heads or Tails
call = input("Call it in air: ").lower()
flip = coin_flip()
if call == flip:
print("You called it right! Point awarded!")
player_score += 1
else:
print("Wrong call! Computer gets point!")
computer_score += 1
Think Ahead
What if we wanted to GIVE the function information when we call it?
Right now, coin_flip() has empty parentheses (). Tomorrow we learn how to pass data INTO functions using parameters!
Next Up: def check_winner(player_choice, coin_result):
Today we master sending data OUT (return). Tomorrow we send data IN!
Optional Extension 3: Function Spotting
Code Architecture
Look at your full Rock, Paper, Scissors program. What repeated code blocks could eventually become their own functions?
Candidate A
Display Score
Printing the current player and computer score banner every round.
show_scores()
Candidate B
Welcome Screen
Printing ASCII art titles and game instructions at the start.
print_welcome()
Candidate C
Get Valid Input
Prompting the user and looping until they pick rock, paper, or scissors.
get_player_choice()
Candidate D
Announce Winner
Printing celebratory winner messages when someone hits 3 points.
show_game_over()
You don't have to code all of these today — just train your eyes to see opportunities for reusable code!
Functions in the Bigger Picture
Mental Model
Variables
Store reusable DATA.
score = 0
Functions
Store reusable CODE.
def coin_flip():
Parameters
Give info TO a function.
(Preview only!)
return
Sends info FROM function back to program.
★ Today's Focus!
Mastering return gives your functions superpowers to communicate with the rest of your app!
Programming Structures Review
The 4 Big Pillars
Pillar 1
Sequence
Instructions happen in order, one line after another from top to bottom.
line 1 → line 2 → line 3
Pillar 2
Selection
The program makes decisions using conditionals.
if / elif / else
Pillar 3
Iteration
The program repeats instructions efficiently.
for / while loops
Pillar 4
Functions
Organize, name, and reuse code blocks containing the other three!
def name(): ... return
You are now writing complete, modular software that utilizes all four fundamental pillars of computing!
Exit Ticket: Closure Questions
Final 5 Minutes
Question 1
What does return do in a function?
Question 2
What is the core difference between print() and return?
Question 3
What exact steps happen when Python executes tiebreaker = coin_flip()?
Question 4
If coin_flip() returns "heads", what value is stored in tiebreaker?
Question 5
Why is a function useful for the coin flip instead of rewriting the coin-flip code every time?
Question 6
What was one bug you found or tested for in your Rock, Paper, Scissors program today?
Record your answers on your guided activity handout before leaving today! Great work!
Returning Values Activity
Computing Foundations • Modular Python Unit
Functions Day 2: Returning Values
Upgrading Rock, Paper, Scissors with a Modular Coin-Flip Tiebreaker
Name:
Date: Period:
Targets: Explain return • Store return value in variable • Use returned data in logic • Test & debug behavior
Part 1: The Core Distinction — print() vs return
print(result) HUMAN
Displays text onto the terminal screen. Once shown, the data is gone. The rest of your Python program cannot inspect or use it in conditionals or scoring.
return result PROGRAM
Hands the value back to the line of code that called the function. The program can catch it in a variable (tie = coin_flip()) to make decisions and award points!
Data Flow Architecture
1. Define def coin_flip():
→
2. Call coin_flip()
→
3. Return return result
→
4. Catch tie = coin_flip()
→
5. Use if tie == "heads":
Part 2: Rock, Paper, Scissors Upgrade Checklist
Check off as you code & test
Step 1: Module Import — Ensure import random is at line 1.
Step 2: Define coin_flip() — Choose "heads" or "tails" and use return.
Step 3: Call inside Tie Condition — In if player == computer:, write tiebreaker = coin_flip().
Step 4: Award Point with Selection — If tiebreaker == "heads", add 1 to player; else add 1 to computer.
Step 5: Game Loop Check — Loop with while until someone reaches 3 points, then announce final winner!
Part 3: Trace & Predict Quick Check
def double(num):
result = num * 2
return result
answer = double(4)
What value is stored in answer?
def coin_flip():
result = random.choice(["heads","tails"])
return result
tiebreaker = coin_flip()
What are the two possible values of tiebreaker?
Functions Day 2 • Student Guided Activity Turn over for Testing Table & Exit Ticket → Page 1 of 2
Part 4: Deliberate Testing & Verification Table
Test behavior deliberately. Do not just check if it runs without crashing!
5 Test Cases
| Test Scenario |
Expected Behavior |
Worked 1st Try? |
What Did You Fix? (or notes) |
| 1. Player Wins Round |
player_score adds 1 |
[ YES / NO ] |
|
| 2. Computer Wins Round |
computer_score adds 1 |
[ YES / NO ] |
|
| 3. RPS Ends in Tie |
coin_flip() is called |
[ YES / NO ] |
|
| 4. Coin Flip Result |
Exactly 1 score increments |
[ YES / NO ] |
|
| 5. Score Reaches 3 |
while loop stops cleanly |
[ YES / NO ] |
|
Part 5: Debugging Analysis — The Ghost Value Bug
def coin_flip():
result = random.choice(["heads", "tails"])
print(result) # <-- Notice this!
tiebreaker = coin_flip()
if tiebreaker == "heads":
player_score += 1
Why will player_score NEVER increase here?
Explanation & Correct Code Fix:
Part 6: Exit Ticket (Individual Reflection)
Complete before end of block
1. In your own words, what does return do in a Python function?
2. What is the fundamental difference between print() and return?
3. What happens during this line of code: tiebreaker = coin_flip()?
4. If coin_flip() returns "heads", what exact value is stored in tiebreaker?
5. Why is a function useful for the coin-flip tiebreaker instead of rewriting the coin-flip code every time?
6. What was one bug or unexpected behavior you found or tested for in your RPS program today?
Functions Day 2 • Student Guided Activity & Exit Ticket Submit to Teacher upon Exit Page 2 of 2