Why Functions?
Without functions, your code repeats itself. Imagine calculating BMI for 100 students โ you'd write the same formula 100 times. Functions let you write it once and use it forever.
Your First Function
def greet():
print("Hello!")
greet() # Call the function
greet() # Call again
greet() # And again
The keyword def defines a function. The parentheses () hold parameters (none here). The indented block is the function body.
Parameters: Giving Functions Information
def greet(name):
print(f"Hello, {name}!")
greet("Chan") # Hello, Chan!
greet("Lee") # Hello, Lee!
name is a parameter โ a variable that holds the value passed in when you call the function.
Multiple Parameters
def introduce(name, age, school):
print(f"My name is {name}.")
print(f"I am {age} years old.")
print(f"I study at {school}.")
introduce("Chan", 17, "Victoria SS")
Return Values: Getting Information Back
def double(n):
return n * 2
result = double(5)
print(result) # 10
print(double(100)) # 200
return sends a value back to wherever the function was called.
The Difference: print vs return
def with_print(n):
print(n * 2) # Shows on screen
def with_return(n):
return n * 2 # Sends value back
x = with_print(5) # Shows 10, x is None
y = with_return(5) # Nothing shown, y is 10
print(x + 1) # Error! can't add 1 to None
print(y + 1) # 11
๐ก Rule of thumb: Use
return when another part of your code needs to use the result. Use print when you just want to show something on screen.Realistic Example: Grade Calculator
def calculate_grade(score):
if score >= 80:
return "A"
elif score >= 65:
return "B"
elif score >= 50:
return "C"
elif score >= 35:
return "D"
else:
return "F"
# Use the function
students = [("Chan", 85), ("Lee", 72), ("Wong", 45)]
for name, score in students:
grade = calculate_grade(score)
print(f"{name}: {grade}")
Default Parameters
def mtr_fare(distance, is_student=True):
fare = distance * 0.5
if is_student:
fare *= 0.5 # 50% discount
return fare
print(mtr_fare(10)) # 2.5 (student)
print(mtr_fare(10, False)) # 5.0 (adult)
Multiple Return Values
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)/len(numbers)
lowest, highest, average = get_stats([85, 72, 91, 68])
print(f"Lowest: {lowest}, Highest: {highest}, Average: {average:.1f}")
Best Practices
- Use lowercase_with_underscores for function names
- Name should describe what it does (
calculate_grade, notcg) - Each function should do one thing well
- Use
returnwhen the caller needs the result - Add a short comment if the purpose isn't obvious
Write Your First 10 Functions in PyForm
Practise defining, calling, and combining functions in a real Python environment โ no installation.
Start Coding Free โ