Quiz 2

Functions — Defining and Using

889 words
4 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Functions — Defining and Using > **Why read this?** As programs grow, you can't keep everything in one long script. Functions are your way of organizing, reusing, and testing code.

Functions — Defining and Using

Why read this? As programs grow, you can't keep everything in one long script. Functions are your way of organizing, reusing, and testing code. Think of them as your own personal commands — you define them once and use them everywhere.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Define functions with def and return values with return
  2. Understand parameters vs arguments
  3. Understand local vs global variable scope
  4. Write functions that solve specific problems
  5. Document functions with docstrings

📋 Prerequisites

  • All previous topics — functions use everything you've learned.

📖 Core Content

21.1 What Problem Do Functions Solve?

Intuition: Imagine you're writing a recipe. The first step says "prepare the sauce." Instead of listing every sauce-making instruction right there, you write "prepare the sauce" and elsewhere define what that means. Functions are the same — they let you name a block of code, then "call" it whenever needed.

21.2 Defining and Calling Functions

python
# runnable
def greet():
    """Print a greeting."""  # docstring
    print("Hello! Welcome to Python.")
# Call the function
greet()
greet()  # can call multiple times
Output:
pseudo
Hello! Welcome to Python.
Hello! Welcome to Python.

21.3 Functions with Parameters

python
# runnable
def greet_person(name):
    """Greet a specific person."""
    print(f"Hello, {name}!")
greet_person("Alice")
greet_person("Bob")
def add(a, b):
    """Return the sum of a and b."""
    result = a + b
    return result
total = add(5, 3)
print(f"5 + 3 = {total}")

21.4 Return Values

python
# runnable
def square(n):
    return n ** 2
def is_even(n):
    return n % 2 == 0
# Functions can return any type
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)
print(square(5))                # 25
print(is_even(7))               # False
print(get_stats([1, 2, 3, 4, 5]))  # (1, 5, 3.0)

21.5 Variable Scope

python
# runnable
x = 10  # GLOBAL variable
def my_func():
    y = 5   # LOCAL variable
    print(f"Inside: x={x}, y={y}")
my_func()
print(f"Outside: x={x}")
# print(y)  # NameError: y is not defined
def modify_global():
    global x  # needed to modify global
    x = 20
modify_global()
print(f"After modify: x={x}")  # 20
Scope rules (LEGB):
  1. Local — inside current function
  2. Enclosing — outer functions (for nested functions)
  3. Global — module level
  4. Built-in — Python's built-in names

21.6 Docstrings

python
# runnable
def calculate_bmi(weight, height):
    """
    Calculate Body Mass Index.
    Args:
        weight: Weight in kilograms
        height: Height in meters
    Returns:
        BMI as a float
    """
    return weight / (height ** 2)
print(calculate_bmi(70, 1.75))
print(calculate_bmi.__doc__)  # prints the docstring

21.7 Worked Example 1: Temperature Converter Functions

python
# runnable
def celsius_to_fahrenheit(c):
    return c * 9/5 + 32
def fahrenheit_to_celsius(f):
    return (f - 32) * 5/9
print(f"100°C = {celsius_to_fahrenheit(100):.1f}°F")
print(f"212°F = {fahrenheit_to_celsius(212):.1f}°C")

21.8 Worked Example 2: Prime Checker Function

python
# runnable
def is_prime(n):
    """Check if n is prime."""
    if n < 2:
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True
# Test
for n in range(1, 20):
    if is_prime(n):
        print(n, end=" ")

21.9 Worked Example 3: Functions Calling Functions

python
# runnable
def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
def combination(n, r):
    """nCr = n! / (r! * (n-r)!)"""
    return factorial(n) // (factorial(r) * factorial(n - r))
print(f"5C2 = {combination(5, 2)}")  # 10
print(f"10C3 = {combination(10, 3)}")  # 120

21.10 Worked Example 4: Validation Wrapper

python
# runnable
def get_positive_number(prompt):
    """Keep asking until user enters a positive number."""
    while True:
        try:
            num = float(input(prompt))
            if num > 0:
                return num
            print("Number must be positive.")
        except ValueError:
            print("Invalid input. Enter a number.")
radius = get_positive_number("Enter radius: ")
area = 3.14159 * radius ** 2
print(f"Area: {area:.2f}")

⚠️ Common Pitfalls

Pitfall 1: Forgetting return

The mistake: Defining a function that calculates but doesn't return.
python
def add(a, b):
    result = a + b  # no return!
print(add(5, 3))  # None
Fix: Add return result.

Pitfall 2: Modifying Global Variables Inside Functions

The mistake: Using x = x + 1 inside a function when x is global — Python creates a NEW local x. Fix: Use global x to declare intent to modify global.

Pitfall 3: Mutable Default Arguments

The mistake: def append_to(item, lst=[]) — the default list is created ONCE and shared. Fix: Use def append_to(item, lst=None): then if lst is None: lst = [].

📝 Practice Questions

Q1: What does this function return?
python
def mystery(x, y):
    return x * 2 + y
print(mystery(3, 4))
Answer: 10 (3*2 + 4 = 10) Q2: Write a function is_palindrome(s) that checks if a string is a palindrome.
Answer:
python
def is_palindrome(s):
    s = s.lower().replace(" ", "")
    return s == s[::-1]
Q3-10: Additional function questions.
(Following pattern.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.