0
0
Pythonprogramming~10 mins

Local scope in Python - Step-by-Step Execution

Choose your learning style9 modes available
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.