Python Learning Series · @onlysamarrr · Day 23 / 30

Day 23: Scope and Recursion

Day 23 teaches scope and recursion. Scope decides where a variable is visible: local inside a function, global outside it. Recursion is when a function calls itself, and it always needs a base case, or it raises RecursionError.

Phase: Intermediate · Reels: 111/450 – 115/450

Quick Answer

Day 23 teaches scope and recursion. Scope decides where a variable is visible: local inside a function, global outside it. Recursion is when a function calls itself, and it always needs a base case, or it raises RecursionError.

What You Will Learn

Code

count = 0

def inc():
    global count
    count += 1
    return count

print(inc())

def fact(n):
    if n <= 1:
        return 1
    return n * fact(n - 1)

print(fact(5))

from functools import lru_cache

@lru_cache
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(10))

Output

1
120
55

Code Explained, Line by Line

  1. global count is needed inside a function to change a global variable; without it you get UnboundLocalError.
  2. fact(n) has base case n <= 1, where it stops. Without a base case recursion never ends.
  3. fact(5) = 5 * 4 * 3 * 2 * 1 = 120.
  4. @lru_cache remembers past answers (memoization), which makes fib fast.
  5. Recursion suits tree-like and nested problems; for simple repetition a loop is enough.
Common Mistake: Forgetting the base case causes RecursionError (stack overflow). Always write the stopping condition first.

Real-Life Use

File trees, JSON data and algorithms like binary search use recursion.

Practice Task: Write fibonacci with recursion and explain the base case of factorial.

Test Yourself — MCQs

Select (tick) an option, then tap Check answer to see instantly whether your answer is right or wrong, with an explanation. You can change your answer and check again.

Q1. What is fact(5)?

Q2. What happens without a base case in recursion?

Q3. What does @lru_cache do?

Today's 5 Reels (from the 90-Day Plan Excel)

111/450ConceptLocal vs global
112/450Live demoRecursion se factorial
113/450Common mistakeBase case bhoolna
114/450QuizQuiz: fibonacci
115/450Interview / real lifeInterview: recursion vs loop
← Day 22Day 24 →