Understanding Functions
A function is a block of code that performs a specific task and can be reused throughout a program. Instead of repeating the same logic multiple times, developers encapsulate it in a function for better modularity and readability.
Example: Repeated Output
Consider a program that needs to print a decorative header multiple times:
print("----------------------------")
print(" Buddha Blessing ")
print("----------------------------")
If this block is needed in multiple places, it's better to encapsulate it in a function to avoid redundancy.
Defining and Calling Functions
Syntax for Function Definition
def function_name():
# Function body
Example:
def displayHeader():
print("----------------------------")
print(" Buddha Blessing ")
print("----------------------------")
Calling a Function
After defining a function, you can call it using its name followed by parentheses:
displayHeader()
Function Documentation
Functions can include a docstring to describe their purpose and usage:
def add_numbers(a, b):
"Adds two numbers and prints the result"
print(a + b)
You can access this documantation using the help() function:
help(add_numbers)
Function Parameters
Passing Data to Functions
Functions can accept parameters to make them more flexible. For example:
def add_numbers(a, b):
result = a + b
print(result)
Calling with Parameters
add_numbers(11, 22)
This allows the function to operate on different inputs dynamically.
Keyword Arguments
Python supports keyword arguments, which allow you to specify parameters by name:
def print_details(name, age):
print(name, age)
print_details(name="Alice", age=30)
However, positional arguments must not follow keyword arguments:
# This will raise a syntax error
print_details(age=30, "Alice")
Returning Values
Functions can return values using the return statement:
def add_numbers(a, b):
return a + b
result = add_numbers(100, 98)
print(result) # Outputs: 198
The returned value can be stored in a variable or used directly.
Types of Functions
Functions can be categorized based on whether they accept parameters or return values:
- No parameters, no return value
- No parameters, has return value
- Has parameters, no return value
- Has parameters, has return value
No Parameters, No Return Value
def show_menu():
print("--------------------------")
print(" Hotpot Ordering System")
print("--------------------------")
No Parameters, Has Return Value
def get_temperature():
return 24
temperature = get_temperature()
print(f"Current temperature: {temperature}")
Has Parameters, No Return Value
def log_message(message):
print(f"Log: {message}")
Has Parameters, Has Return Value
def calculate_sum(num):
total = 0
i = 1
while i <= num:
total += i
i += 1
return total
total_sum = calculate_sum(100)
print(f"Sum from 1 to 100: {total_sum}")
Nested Function Calls
Functions can call other functions, allowing for modular design:
def task_b():
print("Starting task B")
print("Executing task B")
print("Ending task B")
def task_a():
print("Starting task A")
task_b()
print("Ending task A")
task_a()
Output:
Starting task A
Starting task B
Executing task B
Ending task B
Ending task A
Practical Examples
Printing Lines
def print_line():
print("-" * 30)
def print_lines(count):
for _ in range(count):
print_line()
print_lines(3)
Calculating Averages
def sum_three(a, b, c):
return a + b + c
def average_three(a, b, c):
total = sum_three(a, b, c)
return total / 3.0
result = average_three(11, 2, 55)
print(f"Average is {result}")
Variable Scope
Local Variables
Variables defined inside a function are local and inaccessible outside:
def demo():
x = 10
print(x)
demo()
# print(x) # This would raise an error
Global Variables
Variables defined outside functions are global and accessible in all functions:
global_var = 100
def show_global():
print(global_var)
show_global()
Modifying Global Variables
To modify a global variable inside a function, use the global keyword:
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # Outputs: 1
Multiple Return Values
Python functions can return multiple values using tuples:
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder
q, r = divide(5, 2)
print(q, r) # Outputs: 2 1
Function Arguments
Default Arguments
Parameters can have default values:
def print_info(name, age=35):
print(f"Name: {name}, Age: {age}")
print_info(name="Alice") # Uses default age
print_info(name="Bob", age=25) # Overrides default
Variable-Length Arguments
Use *args and **kwargs for variable-length parameters:
def example(a, b, *args, **kwargs):
print(f"a = {a}, b = {b}")
print(f"args = {args}")
for key, value in kwargs.items():
print(f"{key} = {value}")
example(1, 2, 3, 4, x=5, y=6)
Recursion
A function can call itself to solve problems recursively:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5)) # Outputs: 120
Lambda Functions
Anonymous functions created using lambda:
add = lambda x, y: x + y
print(add(10, 20)) # Outputs: 30
Lambda functions are useful for short operations passed as arguments:
students = [{"name": "Alice", "age": 20}, {"name": "Bob", "age": 18}]
students.sort(key=lambda x: x["age"])
print(students)