Some text some message..
Back 11 🧠 What is a Function in Python? 23 Jun, 2025

A function is a block of reusable code that performs a specific task. It helps in making the code modular, readable, and maintainable.


✅ Why Use Functions?

  • Avoid code repetition

  • Make code modular and organized

  • Debug and test specific parts easily


🔹 Defining a Function

➤ Syntax

def function_name(parameters):
    """Optional docstring"""
    # block of code
    return result

➤ Example

def greet(name):
    return f"Hello, {name}!"

print(greet("Abhi"))  # Output: Hello, Abhi!

🧰 Function Components

Component Description
def Keyword to define a function
function_name Name of the function
parameters Optional input variables
return Outputs the result of the function
docstring (Optional) Description of function

🧪 Types of Arguments

➤ 1. Positional Arguments

def area(length, width):
    return length * width

print(area(5, 3))  # Output: 15

➤ 2. Default Arguments

def greet(name="Guest"):
    return f"Hello, {name}!"

print(greet())         # Output: Hello, Guest!
print(greet("Abhi"))   # Output: Hello, Abhi!

➤ 3. Keyword Arguments

print(area(width=4, length=6))  # Output: 24

➤ 4. Variable-Length Arguments

*args (Tuple of positional arguments)

def add_all(*args):
    return sum(args)

print(add_all(1, 2, 3, 4))  # Output: 10

**kwargs (Dictionary of keyword arguments)

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Abhi", role="Data Scientist")

🔁 Return Multiple Values

def get_stats(data):
    return min(data), max(data), sum(data)/len(data)

low, high, avg = get_stats([1, 2, 3, 4, 5])
print(low, high, avg)  # Output: 1 5 3.0

🧠 Lambda (Anonymous) Functions

square = lambda x: x * x
print(square(5))  # Output: 25

🧩 Nested Functions

def outer():
    def inner():
        return "Inner function!"
    return inner()

print(outer())  # Output: Inner function!

🔄 Recursive Function (Function calling itself)

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120

🔬 Complex Example – Fibonacci with Memoization

memo = {}
def fibonacci(n):
    if n in memo:
        return memo[n]
    if n <= 2:
        return 1
    memo[n] = fibonacci(n - 1) + fibonacci(n - 2)
    return memo[n]

print(fibonacci(10))  # Output: 55

🧮 Higher-Order Functions

Functions that take other functions as arguments.

def apply_operation(func, x, y):
    return func(x, y)

def multiply(a, b):
    return a * b

print(apply_operation(multiply, 5, 3))  # Output: 15

📌 Best Practices

✅ Use descriptive function names
✅ Keep functions small and focused
✅ Use docstrings to document purpose
✅ Avoid global variables inside functions