0
0
Pythonprogramming~10 mins

Global scope in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Global scope
Start Program
Define global variable
Define function
Call function
Inside function: Access global variable
Function ends
Program ends
The program starts by defining a global variable, then a function that uses it. When the function is called, it accesses the global variable from the global scope.
Execution Sample
Python
x = 10

def print_x():
    print(x)

print_x()
This code defines a global variable x and a function that prints x, then calls the function.
Execution Table
StepActionVariable 'x' ValueOutput
1Define global variable x = 1010
2Define function print_x()10
3Call print_x()10
4Inside print_x(), print(x)1010
5Function print_x() ends10
6Program ends10
💡 Program ends after function call and output printed
Variable Tracker
VariableStartAfter Step 1After Step 3Final
xundefined101010
Key Moments - 2 Insights
Why does the function print_x() print the value of x even though x is not defined inside it?
Because x is defined in the global scope before the function is called, the function can access it. See execution_table step 4 where print(x) outputs 10.
What if we try to change x inside the function without declaring it global?
Without declaring x as global inside the function, Python treats it as a new local variable. This can cause errors or unexpected behavior. This example only reads x, so no problem occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what value does print_x() print?
A0
B10
Cundefined
DError
💡 Hint
Check the 'Output' column at step 4 in execution_table.
At which step is the global variable x first defined?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for when x is assigned.
If we added 'x = 5' inside print_x() without 'global' keyword, what would happen?
AThe global x changes to 5
BAn error occurs immediately
CA new local x is created inside print_x()
DThe function prints 10
💡 Hint
Recall that assigning to a variable inside a function creates a local variable unless declared global.
Concept Snapshot
Global scope means variables defined outside functions.
Functions can read global variables directly.
To modify global variables inside functions, use 'global' keyword.
Without 'global', assignments create local variables.
Global variables exist throughout program execution.
Full Transcript
This example shows a global variable x set to 10. A function print_x() prints x. When called, print_x() accesses the global x and prints 10. The variable tracker shows x stays 10 throughout. Key points: functions can read global variables without declaring them. But to change them, you must declare 'global x' inside the function. The quiz checks understanding of when x is defined, what print_x() outputs, and what happens if you assign x inside the function without 'global'.