๐Ÿ” 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

โš™๏ธ Function Arguments

๐Ÿ”„ 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

๐Ÿ’ก Common Recursion Examples

๐Ÿงช Interview Questions on Functions & Recursion

  1. What is the difference between a function and a method?
  2. How does Python handle default arguments?
  3. What are *args and **kwargs?
  4. Explain recursion with an example.
  5. How would you prevent a recursion from running infinitely?
  6. What are the advantages of using recursion?
  7. Write a recursive function to calculate the factorial of a number.
  8. Compare recursion with iteration. Which is better and why?
  9. What is a lambda function and where would you use it?
  10. How do you return multiple values from a function?