Functions
Week 1 — Python Basics Revision
Introduction
Functions let you write a block of code once and reuse it anywhere. Instead of copying the same logic over and over, you give it a name and call it whenever needed. Functions are the direct gateway to OOP — in classes, they become "methods."
Defining a Function
def greet():
print("Hello, welcome!")
greet() # Call the function
greet() # Call it again
Use the def keyword, followed by the function name, parentheses, and a colon. The indented lines below form the function body. The function only runs when you call it by name with parentheses.
Functions with Parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
Parameters let you pass data into the function. When you call greet("Alice"), the value "Alice" is assigned to the parameter name inside the function.
Return Values
def add(a, b):
return a + b
result = add(10, 5)
print(result) # 15
# Use directly
print(add(3, 7)) # 10
return sends a value back to wherever the function was called. Without it, the function returns None.
Default Parameters
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
Default parameters have a fallback value. If the caller does not provide one, the default is used. Parameters with defaults must come after parameters without defaults.
Multiple Return Values
def analyze(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
lowest, highest, average = analyze([88, 92, 75, 95])
print(f"Low: {lowest}, High: {highest}, Avg: {average:.1f}")
Python functions can return multiple values separated by commas. You unpack them into separate variables on the left side of the assignment.
Real-World Example
def calculate_discount(price, discount_percent=10):
discount = price * discount_percent / 100
final_price = price - discount
return final_price
# Using the function
laptop = calculate_discount(1000, 15)
mouse = calculate_discount(50)
print(f"Laptop: ${laptop:.2f}") # $850.00
print(f"Mouse: ${mouse:.2f}") # $45.00
This function combines parameters, a default value, and a return statement. You define the logic once and reuse it for any product.
OOP Connection
This is the most important connection. In OOP, functions become methods — they live inside classes. The only difference:
- Function:
def greet(name):— standalone - Method:
def greet(self):— belongs to an object
Instead of calculate_discount(price, 15), you will write product.calculate_discount(15). The object already knows its own price.
If you understand functions, you understand 80% of methods. You are now ready for Week 2: Introduction to OOP.
Best Practices
- Each function should do ONE thing
- Use descriptive verb-based names:
calculate_total,get_name - Return values instead of printing inside functions
- Keep functions short — under 15-20 lines
Common Mistakes
- Forgetting
return— the function returnsNone - Printing inside the function instead of returning (harder to reuse)
- Too many parameters — if more than 4, consider reorganizing
- Calling a function without parentheses:
greetvsgreet()
Practice Exercises
Exercise 1
Write a function is_even(number) that returns True if the number is even, False otherwise.
Exercise 2
Create a function calculate_area(length, width) that returns the area. Use it to calculate areas of 3 different rectangles.
Exercise 3
Write a function create_receipt(item, price, quantity) that returns a formatted string with the total.
Summary
Congratulations — you have completed Week 1! You now understand variables, data types, input/output, conditionals, logical operators, loops, and functions. These are the building blocks of all Python programs.
Starting in Week 2, you will enter the world of Object-Oriented Programming. Variables become attributes. Functions become methods. And your code gets organized into classes and objects. See you there!