Core ConceptPython Functions
A function is a named, reusable block of code that performs a specific task. Instead of writing the same logic over and over, you define it once in a function and call it wherever needed. This is the foundation of the DRY principle — Don't Repeat Yourself.
Functions make code modular (broken into manageable pieces), readable (a good function name explains what it does), and testable (you can test one function in isolation). Every serious Python program is built from functions.
Defining and Calling a Function
Use the def keyword to define a function, followed by the function name, parentheses, and a colon. The indented body below is the code that runs when the function is called.
def greet():
print("Hello, welcome to Python!")
print("Let's build something great.")
# Calling the function — can be called multiple times
greet()
greet()
OutputHello, welcome to Python!
Let's build something great.
Hello, welcome to Python!
Let's build something great.
Parameters and Arguments
Functions become powerful when they accept inputs. Parameters are the variables listed in the function definition. Arguments are the actual values passed when calling the function.
def greet_user(name, role):
print(f"Hello, {name}! You are logged in as {role}.")
greet_user("Alice", "admin")
greet_user("Bob", "viewer")
greet_user("Charlie", "editor")
OutputHello, Alice! You are logged in as admin.
Hello, Bob! You are logged in as viewer.
Hello, Charlie! You are logged in as editor.
Default Parameter Values
You can give a parameter a default value. If the caller does not provide that argument, the default is used. Parameters with defaults must always come after parameters without defaults.
def send_notification(message, channel="email", priority="normal"):
print(f"[{priority.upper()}] Sending via {channel}: {message}")
send_notification("Your order has shipped!")
send_notification("Server is down!", "SMS", "critical")
send_notification("New login detected", priority="high")
Output[NORMAL] Sending via email: Your order has shipped!
[CRITICAL] Sending via SMS: Server is down!
[HIGH] Sending via email: New login detected
The return Statement
The return statement sends a value back to the caller. Once Python hits a return, the function stops immediately and the value is passed back. A function without a return statement returns None by default.
def calculate_discount(price, discount_percent):
discount = price * (discount_percent / 100)
final_price = price - discount
return final_price
original = 250.00
discounted = calculate_discount(original, 20)
print(f"Original: ${original}")
print(f"After 20% discount: ${discounted}")
OutputOriginal: $250.0
After 20% discount: $200.0
Returning Multiple Values
Python functions can return multiple values at once using a tuple. The caller can unpack them directly into separate variables.
def get_user_stats(scores):
total = sum(scores)
average = total / len(scores)
highest = max(scores)
lowest = min(scores)
return total, average, highest, lowest
student_scores = [88, 72, 95, 61, 84]
total, avg, high, low = get_user_stats(student_scores)
print(f"Total: {total}")
print(f"Average: {avg:.1f}")
print(f"Highest: {high}")
print(f"Lowest: {low}")
OutputTotal: 400
Average: 80.0
Highest: 95
Lowest: 61
*args — Variable Positional Arguments
When you do not know how many positional arguments a caller will pass, use *args. It collects all extra positional arguments into a tuple.
def add_all(*numbers):
print(f"Arguments received: {numbers}")
return sum(numbers)
print(add_all(1, 2, 3))
print(add_all(10, 20, 30, 40, 50))
print(add_all(7))
OutputArguments received: (1, 2, 3)
6
Arguments received: (10, 20, 30, 40, 50)
150
Arguments received: (7,)
7
**kwargs — Variable Keyword Arguments
When you do not know what named arguments a caller will pass, use **kwargs. It collects all extra keyword arguments into a dictionary.
def create_profile(name, **details):
print(f"Creating profile for: {name}")
for key, value in details.items():
print(f" {key}: {value}")
create_profile("Alice", age=30, city="Accra", role="engineer")
print("---")
create_profile("Bob", age=25, hobby="chess")
OutputCreating profile for: Alice
age: 30
city: Accra
role: engineer
---
Creating profile for: Bob
age: 25
hobby: chess
Lambda Functions
A lambda is a small, anonymous function defined in a single line. It can have any number of parameters but only one expression. Lambdas are used for short, throwaway functions — most commonly as arguments to built-in functions like sorted(), map(), and filter().
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square_lambda = lambda x: x ** 2
print(square(5))
print(square_lambda(5))
# Lambda as a sort key
employees = [{"name": "Alice", "salary": 75000},
{"name": "Bob", "salary": 92000},
{"name": "Charlie", "salary": 61000}]
sorted_by_salary = sorted(employees, key=lambda emp: emp["salary"])
for emp in sorted_by_salary:
print(f"{emp['name']}: ${emp['salary']}")
Output25
25
Charlie: $61000
Alice: $75000
Bob: $92000
💡Best Practice: Use lambda only for genuinely simple, one-line logic used in one place. If the logic is complex or reused, always define a proper named function with def. Readable code is more valuable than concise code.