Quest 15: Functions Part 3 - Pure Functions & Return Values

Writing Functions That Compute and Return Results

โœจ QUEST 15 | Difficulty: Intermediate | Time: 5 minutes

๐Ÿ“Š Complexity Level: Intermediate โญโญ

Builds on fundamental concepts from earlier quests. Best for students who have completed Quests 1-6 or have some basic programming experience. This explores pure functions and return values.

๐Ÿ’ป Interactive Options:

  • ๐Ÿ““ Open in JupyterLite - Full Jupyter environment in your browser
  • โ–ถ๏ธ Run code directly below - All code cells on this page are editable and runnable
  • ๐Ÿ“ฅ Download Notebook - For use in local Jupyter or Google Colab

๐Ÿ“– Introduction: The Pure Spellcaster

In Quest 14, we explored functions that perform actions but donโ€™t return values. Now weโ€™re going deeper into functions that calculate and return results. These are the workhorses of programming!

Analogy: - Non-returning function: A blacksmith sharpens your sword (side effect, no reward) - Returning function: A merchant appraises your sword and tells you its value (calculation + result)

๐Ÿง™โ€โ™‚๏ธ Story Time: Youโ€™re training with the Grand Mage who teaches you โ€œPure Spellsโ€ โ€” spells that take certain ingredients and always produce the same result. No randomness, no side effects, just pure calculation. The more you master these, the more powerful your code becomes!

๐Ÿ’ก Explanation: Pure Functions & Return Values

A pure function: 1. Takes input (parameters) 2. Computes a result based ONLY on the input 3. Returns that result 4. Has NO side effects (doesnโ€™t modify external state)

# PURE FUNCTION - reliable and predictable
def add(a, b):
    return a + b

# Same inputs always give same output
print(add(3, 4))  # Always 7
print(add(3, 4))  # Always 7

Non-pure function - has side effects:

# NOT PURE - does stuff besides returning
score = 0  # External variable

def play_round():
    global score
    score += 10  # MODIFIES external state!
    return score

๐ŸŽฏ Benefits of Pure Functions

Pure functions are awesome because: - โœ… Predictable: Same input = same output (always!) - โœ… Testable: Easy to test since no hidden dependencies - โœ… Reusable: Works anywhere without side effects - โœ… Debuggable: If it fails, you know itโ€™s the inputs

Example: Calculate with confidence

def calculate_damage(base_power, enemy_defense, critical_hit=False):
    damage = base_power - enemy_defense
    if critical_hit:
        damage = damage * 2
    return damage

# Always works the same way
damage1 = calculate_damage(50, 10, False)  # 40
damage2 = calculate_damage(50, 10, False)  # 40 (same!)
damage3 = calculate_damage(50, 10, True)   # 80

๐ŸŽฎ Activity 1: Math & Calculation Functions

Pure functions for game math:

๐ŸŽฎ Activity 2: String Manipulation Functions

Returning functions for text:

๐ŸŽฎ Activity 3: Data Processing Functions

Functions that transform data:

๐Ÿงฉ Challenge: Implement Game Math Functions

Write a function that: 1. Takes a player level (integer) 2. Returns the base health for that level 3. Use formula: health = 50 + (level * 10)

Then write another function that: 1. Takes current health and max health 2. Returns the percentage as a string like โ€œ75%โ€ 3. Round to nearest integer

โœ… Solution

๐ŸŽ“ Pure Functions vs Side Effects

Use Pure Functions (return values) when: - โœ… Calculating something (math, transformation) - โœ… You want predictable, testable code - โœ… Creating new data from inputs

Use Side Effect Functions (no return) when: - โœ… Displaying information to the player - โœ… Updating game state intentionally - โœ… Logging or recording actions

๐Ÿš€ Whatโ€™s Next?

You now know regular functions that return values. But Python has one more trick: Quest 16: Lambda Functions - tiny anonymous functions perfect for quick calculations!