⚡0 XP🔥0

Variable Scope & Recursion

Lesson 21 of 33 ⏱ 5 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Local vs global variables, the LEGB rule, the global and nonlocal keywords, and how recursive functions work - base case, call stack and examples.

What is scope?#

Scope is the region of a program where a variable can be seen and used.

  • A variable created inside a function is local - it exists only while the function runs.
  • A variable created outside all functions is global - it can be read anywhere in the file.
▶ Try it YourselfPython
Ctrl + Enter to run

Local variables shadow globals#

Assigning to a name inside a function creates a new local variable, even if a global with the same name exists:

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

Local और global को घर और मोहल्ले की तरह समझें:

  • Global variable मोहल्ले का नोटिस बोर्ड है - हर घर (function) उसे पढ़ सकता है।
  • Local variable घर के अंदर की चीज़ है - बाहर वाले उसे नहीं देख सकते, और function खत्म होते ही वह मिट जाता है।

अगर function के अंदर आप count = 5 लिखते हैं, तो Python मोहल्ले के बोर्ड वाला count नहीं बदलता - बल्कि घर के अंदर एक नया count बना देता है। बाहर वाला count पहले जैसा रहता है।

The global keyword#

To modify a global variable inside a function, declare it with global:

▶ Try it YourselfPython
Ctrl + Enter to run

Without global, balance += amount would raise UnboundLocalError - Python sees an assignment and treats balance as local, but it has no value yet.

Tip

Use global sparingly. Functions that take inputs and return outputs are easier to test and reuse:

def deposit(balance, amount):
    return balance + amount

balance = deposit(balance, 500)

The LEGB rule#

When you use a name, Python searches in this order:

Level Meaning
Local inside the current function
Enclosing inside any outer function (for nested functions)
Global at the top level of the file
Built-in Python's built-ins like len, print, max
▶ Try it YourselfPython
Ctrl + Enter to run

nonlocal#

nonlocal lets an inner function modify a variable of the enclosing function:

▶ Try it YourselfPython
Ctrl + Enter to run

Recursion#

A recursive function is a function that calls itself to solve a smaller version of the same problem.

Every recursive function needs:

  1. Base case - a simple input where the answer is known directly (stops the recursion).
  2. Recursive case - the function calls itself with a smaller input, moving towards the base case.

Example: factorial#

5! = 5 × 4 × 3 × 2 × 1. Notice that 5! = 5 × 4!, and 4! = 4 × 3!, and so on.

▶ Try it YourselfPython
Ctrl + Enter to run

How it runs - the call stack#

factorial(4)
= 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))          <- base case reached
= 24

Each call waits for the smaller call to finish. Python keeps these waiting calls on the call stack.

हिंदी में समझें

Recursion को रूसी गुड़िया (Matryoshka doll) की तरह समझें - हर गुड़िया के अंदर एक छोटी गुड़िया होती है, जब तक सबसे छोटी गुड़िया न आ जाए जो खुलती नहीं।

  • सबसे छोटी गुड़िया = base case (जहाँ रुकना है, जैसे n <= 1 तो जवाब 1)
  • हर बार बड़ी गुड़िया खोलकर छोटी निकालना = recursive case (factorial(n - 1) - हर बार problem छोटी होती है)

अगर base case न हो, तो function खुद को अनगिनत बार बुलाता रहेगा और Python RecursionError दे देगा।

▶ Try it YourselfPython
Ctrl + Enter to run

Example: power and sum of a list#

▶ Try it YourselfPython
Ctrl + Enter to run

Recursion limits#

Common Mistake

Python limits recursion depth (about 1000 calls by default). Forgetting the base case, or very deep recursion, gives:

RecursionError: maximum recursion depth exceeded

For simple repetition, a loop is usually faster and safer. Recursion shines for naturally recursive problems: tree structures, folders inside folders, divide-and-conquer algorithms (merge sort, quick sort), and backtracking puzzles.

Summary#

  • Local variables live inside a function; global variables live at file level.
  • Assigning inside a function creates a local; use global (or better, return values) to change globals.
  • Name lookup follows LEGB; nonlocal modifies an enclosing function's variable.
  • Recursion = a function calling itself, with a base case and a smaller recursive case.
  • Missing base case → RecursionError.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Recursive sum of digits

Write a recursive function digit_sum(n) that returns the sum of the digits of a non-negative integer.

2

Fibonacci

Write a recursive fib(n) that returns the n-th Fibonacci number, where fib(0) = 0, fib(1) = 1, and fib(n) = fib(n-1) + fib(n-2).

3

Counter with global

Complete visit() so that each call adds 1 to the global variable visits. After the three calls, print(visits) must show 3.

Expected output:
3

Quick Quiz

Q1.

What is printed?

x = 10
def f():
    x = 5
f()
print(x)
Q2.

What does the global keyword do inside a function?

Q3.

What is a base case in recursion?

Q4.

In which order does Python search for a name (LEGB)?

Q5.

What is fact(4) if def fact(n): return 1 if n <= 1 else n * fact(n - 1)?