Reusable Functions
Master functions to avoid code duplication, pass parameters, return values, and manage variable scopes.
1. The DRY Principle
DRY stands for Don't Repeat Yourself. Instead of copying and pasting code, bundle it into a function and call it whenever needed.
2. Defining and Calling Functions
We define a function using the def keyword, followed by a name, parentheses for parameters, and a colon. Code blocks inside must be indented by 4 spaces.
3. Parameters vs. Arguments
- Parameters: Variables listed in the function definition (e.g.,
x,y). - Arguments: Actual values passed to the function when calling it (e.g.,
5,10).
4. Return values & Scope
Use the return keyword to send values back to the caller. Variables defined inside a function have local scope and cannot be accessed outside the function block. To modify a global variable, declare it using the global keyword.
💻 Python Code Examples
Example 1: Simple Static Procedure
def sayHello():
print("Hello beginner class!")
sayHello()
Description: Defines a simple function without parameters and calls it.
Example 2: Function with Parameters
def greet(name):
print(f"Hello {name}!")
greet("Peter")
Description: Defines a function with a name parameter, passing 'Peter' as an argument.
Example 3: Functions with Return Values
def add(x, y):
return x + y
result = add(5, 10)
print(result)
Description: Calculates a value and returns it to the caller.
Example 4: Returning Multiple Values
def getMinMax(numbers):
return min(numbers), max(numbers)
lo, hi = getMinMax([3, 1, 5])
print(lo, hi)
Description: Returns multiple values as a tuple, which is unpacked when calling the function.
Example 5: Demonstrating Variable Scope
g_val = 100
def checkScope():
l_val = 50
print(l_val)
checkScope()
Description: Accesses a local variable inside the function. Accessing l_val outside would raise a NameError.
Example 6: Modifying Global Variables
val = 10
def change():
global val
val = 20
change()
print(val)
Description: Uses the global keyword to modify a global variable inside a function.
🧠 Active Retrieval Quizzes
Answer the following 10 multiple-choice questions to test your storage strength.
Question 1: What does the DRY principle stand for in programming?
Question 2: Which keyword is used to define a function in Python?
Question 3: What is the difference between parameters and arguments?
Question 4: What happens when a function encounters the return keyword?
Question 5: What is a local variable scope?
Question 6: What error is raised if you print a local variable outside its function?
Question 7: How can you modify a global variable inside a function?
Question 8: What does a function return by default if no return statement is specified?
Question 9: What is the output of def f(): pass; print(f())?
Question 10: What character must end a function definition header line?
🖥️ Output Prediction Challenges
Read each code snippet carefully, analyze its execution flow, and predict the exact string result written to the console.
Predict the output of the code snippet below. Type the exact output in the console.
def greet():
return "Hi"
print(greet())
Predict the output of the code snippet below. Type the exact output in the console.
def add(x, y):
return x + y
print(add(2, 3))
Predict the output of the code snippet below. Type the exact output in the console.
def double(val):
return val * 2
print(double(double(2)))
Predict the output of the code snippet below. Type the exact output in the console.
x = 5
def f():
global x
x = 10
f()
print(x)
Predict the output of the code snippet below. Type the exact output in the console.
def f():
return 5
return 10
print(f())
🎮 Interactive Code Playground
Type your own Python code below and click "Run Code" to execute it instantly in your browser!
Console ready.
Stuck on any concept, or want to explore an edge case? Don't hesitate to ask follow-up questions to your instructor! Active questioning helps build storage strength.
📋 Progress Status
📌 Check the box above to mark this weekend's lesson complete. Your dashboard status ring will update automatically.