Chapter 10: Functions
Modularize and reuse your code. Learn how built-in functions take inputs to return values, distinguish sorted functions from mutable list methods, pass dynamic parameters, and manage namespace scope boundaries.
Why Do We Need Functions?
In programming, duplicate code blocks are highly inefficient and hard to maintain. A function is a reusable block of code that performs a specific task. By wrapping code inside a function definition, we can call it repeatedly with different inputs, keeping our main application logic short, clean, and organized.
Let's first explore how parameters enter a function scope and return outputs back to the caller.
10.1 Function Anatomy & Execution Stepper
In Python, you define a custom function using the def keyword, followed by the function name, its arguments in parentheses, and a colon. Code blocks inside must be indented.
Slide to set an input value for argument a, then click Step Path to trace how variables move from global context into the function scope and return a mutated value.
val = 5
b = a + 1
result = ?
This is the code structure mapped in the interactive simulator above:
# Defining our custom function
def add1(a):
b = a + 1
return b
# Calling the function and storing the returned result
result = add1(5)
print("Function Output:", result)
10.2 Functions vs Methods
Python contains both **Built-in Functions** and **Object Methods**. While they perform similar computational tasks, their execution paths differ:
- Functions (e.g.
sorted(list)): Accept inputs as arguments and return a **new** sorted copy, leaving the original object unchanged. - Methods (e.g.
list.sort()): Are tied directly to the object and mutate/modify the original object **in-place** (returning no new list).
Click on the buttons to trigger either the sorted() built-in function or the list sort() method, and observe how lists are altered.
Compare these two code execution cases to understand in-place mutations:
# Case 1: Built-in function
ratings = [10, 9.5, 8.0, 7.0, 9.0]
sorted_ratings = sorted(ratings)
print("Original list ratings remains unchanged:", ratings)
# Case 2: Object method
ratings.sort()
print("Original list ratings is modified in-place:", ratings)
10.3 Parameters & Polymorphism
Python arguments possess **polymorphic** features. This means a function can accept parameters of varying data types, and dynamically adapt its computational meaning depending on what it receives.
Select parameter types and inputs below to observe how functions adapt polymorphic calculations, or bundle parameters into a variadic tuple using the *args asterisk prefix.
Here is the polymorphic and variadic packing code syntax:
# Polymorphic function
def mult(a, b):
return a * b
print(mult(2, 3)) # Output: 6
print(mult(2, "Michael Jackson")) # Output: "Michael JacksonMichael Jackson"
# Variadic packing function
def printNames(*names):
for name in names:
print(name)
printNames("Thriller", "Bad") # Packs 2 arguments into a tuple
10.4 Namespace Scope Boundaries
The **Scope** of a variable dictates where in the code that variable is visible and accessible. Variables declared outside functions sit in the **Global Scope** and are visible everywhere. Variables declared inside a function sit in its **Local Scope** and are deleted/freed once the function finishes executing.
Observe how namespaces isolate variables. Check how Python searches local context first before falling back to global definitions, or use the global keyword to override bounds.
This is the local-to-global hierarchy logic illustrated in the sandbox:
# Example 1: Local variable takes priority
date = 2017 # Global variable
def thriller():
date = 1982 # Local variable
return date
print(thriller()) # Prints 1982 (Local scope)
print(date) # Prints 2017 (Global scope remains unchanged)
# Example 2: Accessing global variables from local scopes
ratings = 9 # Global variable
def printRatings():
print(ratings) # No local ratings exist, checks and uses global value
# Example 3: Defining global variables inside functions
def pinkFloyd():
global claimed_sales
claimed_sales = "45 million" # Modifies the variable in the global scope
Practice Quiz
Test your understanding of functions, parameter polymorphism, and scope namespaces by answering the questions below.