Python Learning Series · @onlysamarrr · Day 23 / 30
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
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.
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))
1 120 55
File trees, JSON data and algorithms like binary search use recursion.
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?
| 111/450 | Concept | Local vs global |
| 112/450 | Live demo | Recursion se factorial |
| 113/450 | Common mistake | Base case bhoolna |
| 114/450 | Quiz | Quiz: fibonacci |
| 115/450 | Interview / real life | Interview: recursion vs loop |