Functions & Recursion in Python

Break your code into smaller, reusable parts using functions

🧩 What is a Function?

Detail Explanation

A function is a reusable block of code that performs a specific task. It helps in reducing code duplication and improves code readability.

Functions can take parameters and can return values.

🛠️ Defining and Calling Functions

def greet(name):
    print("Hello,", name)

greet("Rohan")

Output: Hello, Rohan

⚙️ Return Statement

def add(a, b):
    return a + b

result = add(3, 5)
print("Sum:", result)

Output: Sum: 8

🔁 What is Recursion?

Recursion is a technique used to solve problems by breaking them down into smaller subproblems of the same type.

Every recursive function must have a base case to avoid infinite loops.

🧠 Recursion Example

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

print(factorial(5))

Output: 120

✅ When to Use Recursion?