Bird
Raised Fist0
Pythonprogramming~10 mins

Local scope in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Local scope
Start function
Create local variables
Use local variables
Function ends
Local variables destroyed
When a function runs, it creates its own local variables that exist only inside it. After the function finishes, these variables disappear.
Execution Sample
Python
def greet():
    message = "Hello"
    print(message)

greet()
This code defines a function with a local variable and prints it when the function is called.
Execution Table
StepActionLocal VariablesOutput
1Function greet() is calledmessage: undefined
2Local variable message created with value 'Hello'message: 'Hello'
3print(message) outputs messagemessage: 'Hello'Hello
4Function greet() ends, local variables destroyedmessage: destroyed
💡 Function ends, local variable 'message' no longer exists
Variable Tracker
VariableStartAfter Step 2After Step 3Final
messageundefined'Hello''Hello'destroyed
Key Moments - 2 Insights
Why can't we use the variable 'message' outside the function?
Because 'message' is local to the function as shown in step 4 of the execution_table, it is destroyed when the function ends and does not exist outside.
What happens if we try to print 'message' before it is created inside the function?
The variable 'message' is undefined before step 2, so trying to use it before creation would cause an error.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'message' at Step 3?
Aundefined
B'Hello'
Cdestroyed
DNone
💡 Hint
Check the 'Local Variables' column at Step 3 in the execution_table.
At which step does the local variable 'message' get destroyed?
AStep 2
BStep 3
CStep 4
DNever destroyed
💡 Hint
Look at the 'Action' column in the execution_table describing function end.
If we try to print 'message' outside the function, what will happen?
AIt will cause an error
BIt will print None
CIt will print 'Hello'
DIt will print an empty string
💡 Hint
Refer to the key_moments explanation about variable scope and destruction.
Concept Snapshot
Local scope means variables created inside a function exist only there.
They are created when the function runs and destroyed when it ends.
You cannot use local variables outside their function.
Trying to access them outside causes an error.
Full Transcript
Local scope means variables defined inside a function are only available inside that function. When the function starts, local variables are created. When the function ends, these variables are destroyed and no longer exist. For example, in the code, the variable 'message' is created inside the function greet and printed. After greet finishes, 'message' is destroyed. If you try to use 'message' outside greet, it will cause an error because it does not exist there.

Practice

(1/5)
1. What does local scope mean in Python?
easy
A. Variables can be used anywhere in the program
B. Variables exist only inside the function where they are created
C. Variables are shared between all functions
D. Variables are stored permanently on the disk

Solution

  1. Step 1: Understand the meaning of local scope

    Local scope means a variable is created inside a function and only exists there.
  2. Step 2: Compare options with this meaning

    Only Variables exist only inside the function where they are created correctly states that variables exist only inside their function.
  3. Final Answer:

    Variables exist only inside the function where they are created -> Option B
  4. Quick Check:

    Local scope = variables inside function only [OK]
Hint: Local variables live only inside their function [OK]
Common Mistakes:
  • Thinking local variables can be used outside the function
  • Confusing local scope with global scope
  • Believing variables are shared across functions
2. Which of the following is the correct way to define a local variable inside a function?
easy
A. def func(): x = 5
B. x = 5 def func(): print(x)
C. def func(): global x x = 5
D. def func(): return x

Solution

  1. Step 1: Identify local variable definition

    A local variable is created by assigning a value inside a function without global keyword.
  2. Step 2: Check each option

    def func(): x = 5 assigns x inside the function, making it local. Others either use global or no assignment inside function.
  3. Final Answer:

    def func():\n x = 5 -> Option A
  4. Quick Check:

    Assign inside function = local variable [OK]
Hint: Assign variable inside function without global for local [OK]
Common Mistakes:
  • Using global keyword when not needed
  • Assigning variable outside function expecting it local
  • Trying to return variable not defined inside function
3. What will be the output of this code?
def greet():
    message = "Hello"
    print(message)

greet()
print(message)
medium
A. Hello NameError
B. Hello Hello
C. NameError Hello
D. NameError NameError

Solution

  1. Step 1: Understand variable scope in the code

    Variable 'message' is defined inside greet(), so it is local to that function.
  2. Step 2: Trace the print statements

    Calling greet() prints 'Hello'. Then print(message) outside function causes NameError because 'message' is not defined globally.
  3. Final Answer:

    Hello\nNameError -> Option A
  4. Quick Check:

    Local variable outside function causes NameError [OK]
Hint: Local variables can't be printed outside their function [OK]
Common Mistakes:
  • Assuming local variable is accessible globally
  • Expecting both prints to show 'Hello'
  • Ignoring NameError on second print
4. Find the error in this code and fix it:
def add():
    result = a + b
    print(result)

add()
Assuming a = 2 and b = 3 are defined outside the function.
medium
A. Add 'global a, b' inside add()
B. No error, code runs fine
C. Define a and b inside add()
D. Pass a and b as parameters to add()

Solution

  1. Step 1: Identify variable scope issue

    a and b are defined outside but used inside add() without global or parameters, causing NameError.
  2. Step 2: Fix by passing variables as parameters

    Passing a and b as parameters to add() allows access without global keyword.
  3. Final Answer:

    Pass a and b as parameters to add() -> Option D
  4. Quick Check:

    Use parameters to access outside variables inside function [OK]
Hint: Pass outside variables as parameters to use inside function [OK]
Common Mistakes:
  • Using global keyword unnecessarily
  • Defining variables inside function losing outside values
  • Ignoring NameError from missing variables
5. How can you modify this code to keep track of how many times count_calls() is called, using local scope only?
def count_calls():
    calls = 0
    calls += 1
    print(f"Called {calls} times")

count_calls()
count_calls()
hard
A. Declare calls as global variable
B. Define calls outside function and modify inside
C. Use a default argument to store calls count
D. Use a class to store calls count

Solution

  1. Step 1: Understand why calls resets

    Variable calls is local and resets to 0 each call, so count never increases.
  2. Step 2: Use default argument to keep state locally

    Using a default argument like calls=[0] keeps count inside function without global or external variables.
  3. Final Answer:

    Use a default argument to store calls count -> Option C
  4. Quick Check:

    Default argument keeps local state across calls [OK]
Hint: Use default mutable argument to keep count inside function [OK]
Common Mistakes:
  • Using global variable instead of local trick
  • Defining calls outside function losing local scope
  • Not realizing local variables reset each call