What is meant by scope of a variable?
Scope of a variable refers to the part of the program from where you can access the variable. In simpler words, it refers to the area of the code where you can use a particular variable.
We will be taking a quick overview of Local and Global variables here.
What is meant by a Global variable?
1. A variable which is declared in Global scope or outside a function is called a Global variable.
2. If you create more than one global variable with same name, the last one will override the previous.
3. You can access a Global variable from any part of your program.
What is meant by a Local variable?
1. A variable which is declared inside a function is called a Local Variable. Its scope is local and limited to that function.
2. You can have local variables with the same name in different functions.
3. You cannot access a local variable from outside that function. It will throw a
Lets take a question I came across in the community to understand the concept.
a=1 b= def func(a,b): a+=1 b+= func(a,b) print(a in b)
What will be the output and explain why?
Spend some time reading more about scope before jumping to the solution.
The Answer is TRUE
A few points to know before jumping to the code:-
- Anything that is defined outside a function has global scope. Therefore
a = 1 and b = are global variables.
- Variables defined inside a function are local to that function and can be accessed from the point they are defined until the end of the function and exist as long as the function is executing.
- When you use an assignment statement, by default it creates variables in local scope instead of modifying the global variable.
- If a local variable has the same name as the global variable, the local variable will always be considered more important.
- Reassigning a variable inside a function won't change the variable you passed as an argument outside the function. Performing mutable operations on the variable, however, will change it.
Having read above points, lets move to the code.
Inside the function you append the value of
a = 2 and list
b = [10,1]. Considering above points, the
local variable a is not the same as
global variable a. So any assignment made will not change the
global variable a, but create a new
local variable a (Point 4). Where as list being a mutable object, the
global variable b gets modified (Point 5).
After executing the function the
local variable a (with value = 2) is no longer accessible (Point 2) and the print statement points at global variable
a = 1 and
b = [10,1].
print(a in b) evaluates to
There are other terms regarding scope like the keywords global , nonlocal, etc..
This was just a brief explanation with a basic example. For detailed explanation explore the concept - "Scope of a Variable".
Hope this helps you understand the scope concept a bit.