๐ Day 5: Functions and Recursion in Python
๐ What is a Function?
A function is a block of organized, reusable code used to perform a single, related action.
๐ ๏ธ How to Define and Call a Function
def greet():
print("Hello, World!")
greet()
๐งฉ Types of Functions
- Built-in functions (e.g.,
print()
, len()
)
- User-defined functions
- Lambda functions (anonymous functions)
โ๏ธ Function Arguments
- Default arguments:
def greet(name="Guest")
- Keyword arguments:
greet(name="Alice")
- Variable-length:
*args
, **kwargs
๐ Return Statement
Use return
to send a result back from the function.
โก Lambda Functions
One-line anonymous function: square = lambda x: x*x
๐ง What is Recursion?
Recursion is a process in which a function calls itself directly or indirectly.
โ
Base Case & Recursive Case
def factorial(n):
if n == 0:
return 1 # base case
return n * factorial(n - 1) # recursive case
๐ Recursion vs Iteration
- Recursion is elegant and closer to mathematical logic.
- Iteration uses loops and is generally more memory efficient.
๐ก Common Recursion Examples
- Factorial of a number
- Fibonacci series
- Sum of digits
- GCD calculation
๐งช Interview Questions on Functions & Recursion
- What is the difference between a function and a method?
- How does Python handle default arguments?
- What are
*args
and **kwargs
?
- Explain recursion with an example.
- How would you prevent a recursion from running infinitely?
- What are the advantages of using recursion?
- Write a recursive function to calculate the factorial of a number.
- Compare recursion with iteration. Which is better and why?
- What is a lambda function and where would you use it?
- How do you return multiple values from a function?