Content on Functions
1. What Are Functions?
Functions are reusable blocks of code designed to perform a specific task.
They help make programs:
● Reusable: Write a piece of code once and call it multiple times.
● Maintainable: Modify a single function to update all calls to it.
● Organized: Divide complex programs into smaller, logical units.
Key Features of Functions:
1. Encapsulation: Functions bundle related logic together.
2. Abstraction: Users of a function don’t need to know its internal
workings; they just call it.
3. DRY Principle: Avoid code repetition with functions (Don't Repeat
Yourself).
2. Defining and Calling Functions
A function must be defined before it can be called.
2.1 Defining a Function
Syntax:
def function_name(parameters):
# Function body
return value # Optional
Example:
def greet_user(name):
print(f"Hello, {name}!")
● def: Defines a function.
● function_name: Name of the function (should describe what it
does).
● parameters: Inputs to the function (optional).
● Function body: Indented code block containing the logic.
2.2 Calling a Function
To execute a function, call it using its name and provide arguments if
required.
Example:
greet_user("Alice")
Output:
Hello, Alice!
3. Parameters and Arguments
Parameters: Variables defined in the function definition to accept inputs.
Example:
python
Copy code
def add(a, b): # a and b are parameters
return a + b
Arguments: Values provided to the function when calling it.
Example:
print(add(3, 5)) # 3 and 5 are arguments
Default Parameters: Provide default values if no argument is passed.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
4. Fruitful Functions (Returning Values)
Functions can return values using the return statement.
Example:
def square(number):
return number * number
result = square(4)
print(f"The square is {result}.")
Output:
The square is 16.
5. Types of Functions
1. Built-In Functions: Provided by Python, e.g., print(), len(),
range().
2. User-Defined Functions: Created by the programmer for specific
needs.
Comparison:
Feature Built-In User-Defined
Functions Functions
Purpos General-purpose Specific to the
e tasks program
Exampl sum(), calculate_total(
es input() ), greet()
6. Advanced Features of Functions
Positional and Keyword Arguments:
def describe_pet(animal, name):
print(f"{name} is a {animal}.")
describe_pet("dog", "Buddy") # Positional
arguments
describe_pet(animal="cat", name="Kitty") # Keyword
arguments
1.
Arbitrary Arguments: Use *args for variable-length arguments.
def add_numbers(*args):
return sum(args)
print(add_numbers(1, 2, 3, 4)) # Output: 10
Arbitrary Keyword Arguments: Use **kwargs for variable-length
keyword arguments.
def print_user_details(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_user_details(name="Alice", age=25, city="Paris")
7. Best Practices
Use Meaningful Names: Function names should clearly indicate
their purpose.
○ Good: calculate_area(), send_email()
○ Bad: func1(), do_stuff()
Keep Functions Small: Each function should perform one specific
task.
Document Functions: Use comments or docstrings to explain what the
function does.
def calculate_area(radius):
"""Calculates the area of a circle given its
radius."""
return 3.14 * radius ** 2
Avoid Global Variables: Pass required data as parameters instead
of relying on global variables.
Thinking Points
1. Why is it better to use functions instead of repeating code?
2. What happens if you call a function without providing required
arguments?
3. How can you improve the readability of complex functions?