Understand local and global variable scope
Programming Concepts: Variable Scope 📚
What is a Variable? 📌
A variable is like a box that holds a value. The name of the box is the variable name. For example, you can write x = 5 or y = 10 and later use x or y in your calculations.
In math notation, we often write $x = 5$ or $y = 10$ to show the value stored in the variable.
Local Variables 🗂️
Local variables are created inside a function and can only be used inside that function.
Analogy: Think of a local variable as a sticky note you put on a specific page of your notebook. Only you can see it when you look at that page.
def calculate():
result = 10 # local variable
return result
Here, result exists only inside calculate(). Outside, it is invisible.
The function f(x) = x^2 can be written as:
$$f(x) = x^2$$
Global Variables 🌐
Global variables are defined outside any function and can be accessed anywhere in the program.
Analogy: A global variable is like a whiteboard in the classroom that everyone can see and write on.
total = 0 # global variable
def add(value):
global total
total += value
Here, total can be read or changed by any function that declares it as global.
Scope Rules in a Nutshell 🥜
- Variables defined inside a function are local to that function.
- Variables defined outside all functions are global.
- Inside a function, if you want to modify a global variable, you must declare it with
global. - Local variables hide global variables of the same name within the function.
| Variable | Scope | Where Can It Be Used? |
|---|---|---|
| x | Local | Only inside the function where x is defined. |
| y | Global | Anywhere in the program after it is defined. |
Exam Tip 📚
When answering questions about variable scope:
- Identify where the variable is defined.
- Determine if it is inside a function (local) or outside (global).
- Remember that a local variable with the same name as a global one will shadow the global variable within its function.
Use the word shadow to show you understand the concept.
Revision
Log in to practice.