Variable Scope
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Variable Scope
Definition: Variable scope refers to the region of a program where a particular variable is accessible and can be used. In Python, variables can have either a local scope or a global scope.
Why: Scope is an important concept when working with functions because it prevents different parts of your program from accidentally changing or breaking variables they shouldn't have access to.
Types of Scope
- Global Scope: A variable created in the main body of the Python script is a global variable. It can be seen and accessed by any code in the file, including inside functions.
- Local Scope: A variable created inside a function belongs to the local scope of that function. It can only be used inside that specific function and cannot be accessed from the outside.
Example
x = 100 # Global variable
def show():
y = 20 # Local variable
print(x) # Accessing global variable inside the function
print(y) # Accessing local variable inside the function
show()
# print(y) # This would cause a NameError because y does not exist outside show()
Explanation
xis declared outside the function, making it a global variable. Theshow()function can read its value without any issues.yis declared inside theshow()function, making it a local variable. It is created when the function is called and destroyed as soon as the function finishes executing.- If you uncomment the last line of the example, the program will crash because the main script has no idea what
yis.
Key Notes
- If you want to modify a global variable from inside a function, you must declare it using the
globalkeyword (e.g.,global x) inside the function before changing it. - If a local variable and a global variable share the exact same name, Python will prioritize the local variable when executing code inside that specific function.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute