Functions and Methods – Reusable Code Blocks and the DRY Principle
You have written a few lines of code. It works. But then you realize you need to do the same calculation in five different places. Copy-pasting the same code five times is messy, error-prone, and a nightmare to change later. Enter functions – reusable blocks of code that you can call by name.
1. What Is a Function?
A function is a named block of code that performs a specific task. You "call" the function by its name, and the computer executes the code inside it.
def greet():
print("Hello, welcome to the program!")
# Call the function
greet()
2. Parameters and Arguments
Parameters are variables listed in the function definition. Arguments are the actual values you pass when calling.
def greet_user(name):
print("Hello, " + name + "!")
greet_user("Alice") # prints: Hello, Alice!
greet_user("Bob") # prints: Hello, Bob!
# Multiple parameters
def rectangle_area(length, width):
area = length * width
print("Area is", area)
rectangle_area(5, 3) # Area is 15
3. Return Values
def add(a, b):
result = a + b
return result
total = add(10, 20)
print(total) # 30
# Multiple return values (using tuples)
def circle_stats(radius):
area = 3.14159 * radius * radius
circumference = 2 * 3.14159 * radius
return area, circumference
a, c = circle_stats(5)
print(f"Area: {a}, Circumference: {c}")
4. Scope – Where Variables Live
Variables defined inside a function are local – they cannot be accessed outside. Variables defined outside any function are global.
def my_func():
x = 10 # local variable
print(x)
my_func()
# print(x) # ERROR! x is not defined outside the function
Good practice: Avoid global variables. Pass everything as parameters and return results.
5. The DRY Principle – Don't Repeat Yourself
# Without functions (bad – repetitive)
area1 = 5 * 3
print(area1)
area2 = 7 * 2
print(area2)
area3 = 10 * 4
print(area3)
# With functions (good – DRY)
def area(length, width):
return length * width
print(area(5, 3))
print(area(7, 2))
print(area(10, 4))
If you later need to change the formula, you change it in one place, not three.
6. Methods – Functions Attached to Objects
A method is a function that belongs to an object. You call it using dot notation: object.method().
name = "alice"
print(name.upper()) # "ALICE"
print(name.capitalize()) # "Alice"
numbers = [3, 1, 4, 1, 5]
numbers.sort() # sorts the list in place
numbers.append(9) # adds 9 at the end
7. Example – A Simple Calculator with Functions
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Error: Division by zero"
return a / b
# Main program
print("Simple Calculator")
while True:
op = input("Enter operation (+, -, *, /) or 'q' to quit: ")
if op == 'q':
break
if op not in ['+', '-', '*', '/']:
print("Invalid operation")
continue
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if op == '+':
result = add(num1, num2)
elif op == '-':
result = subtract(num1, num2)
elif op == '*':
result = multiply(num1, num2)
elif op == '/':
result = divide(num1, num2)
print(f"Result: {result}\n")
8. Common Mistakes
|
Mistake |
Why it fails |
Fix |
|
Forgetting to return a value |
The function returns None, causing unexpected results. |
Add a return statement. |
|
Using a variable inside a function without passing it |
The function looks for a variable that does not exist in its scope. |
Pass it as a parameter. |
|
Defining a function but never calling it |
No output; code inside never runs. |
Add a call: function_name() |
Summary
|
Term |
Definition |
|
Function |
Reusable block of code with a name. |
|
Parameter |
Variable in the function definition that receives an argument. |
|
Argument |
Actual value passed to a function when called. |
|
Return value |
Value that the function sends back to the caller. |
|
Local variable |
Variable defined inside a function; not accessible outside. |
|
DRY |
Don't Repeat Yourself – principle of avoiding duplicate code. |
|
Method |
A function that belongs to an object (e.g., "hello".upper()). |
Review Questions
- Write a function called is_even that takes an integer and returns True if it is even, False otherwise.
- What is the output of the following code?
def test(x):
x = x + 5
return x
y = 10
result = test(y)
print(y, result) - Explain why using functions makes a program easier to maintain than copy-pasting the same code multiple times.