User-Defined Functions in Python
1. Introduction to Functions
• Definition: A function is a reusable block of code that performs a specific task.
• Types:
o Built-in functions (e.g., print(), len())
o User-defined functions (created by the programmer)
• Analogy: A coffee machine – press a button (call function), it does the work inside,
and gives you coffee (result).
2. Why Use Functions?
• Avoid code duplication (DRY Principle)
• Improve readability & organization
• Make debugging easier
• Break complex problems into smaller parts (modularity)
Where they are used:
• Data processing
• Repeated calculations
• Automating tasks
3. Syntax of a Function
def function_name(parameters):
"""Optional docstring"""
# code block
return result
Parts:
• def → keyword to define function
• function_name → meaningful name
• parameters → input values (optional)
• return → output value (optional)
4. Types of User-Defined Functions
1. Without parameters
def greet():
print("Hello, Students!")
2. With parameters
def greet(name):
print(f"Hello, {name}!")
3. With default parameters
def greet(name="Guest"):
print(f"Hello, {name}!")
4. Returning a value
def add(a, b):
return a + b
5. Multiple returns
def stats(numbers):
return max(numbers), min(numbers), sum(numbers)/len(numbers)
5. How Functions Optimize Code
• Write once, use multiple times
• Debugging is easier (change in one place)
• Increases productivity
• Improves modularity
Example:
def square(x):
return x * x
def sum_of_squares(a, b):
return square(a) + square(b)
6. * and ** concept
*args (Positional arguments)
def add_numbers(*args):
return sum(args)
print(add_numbers(2, 4, 6))
**kwargs (Keyword arguments)
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
print_info(name="Rahul", course="Python")
Using both
def example(*args, **kwargs):
print(args, kwargs)
example(1, 2, 3, name="Rahul", city="Delhi")
7. Real-Life Use Case Example
Scenario: Calculating student grades
def calculate_result(name, **marks):
total = sum([Link]())
percentage = total / len(marks)
return f"{name} scored {percentage:.2f}%"
print(calculate_result("Aarav", Math=88, Science=92, English=81))
print(calculate_result("Isha", Math=76, Science=85, English=90))
Benefits:
• Handles any number of subjects
• Flexible and reusable
• Easy to update formula
8. Summary
• Functions make code cleaner, reusable, and modular
• *args and **kwargs provide flexibility in passing arguments
• Functions can work together to form bigger systems
• Real-life problems become easier to solve using functions