- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Global and Local Variables in Python?
There are two types of variables: global variables and local variables. The scope of global variables is the entire program whereas the scope of local variable is limited to the function where it is defined.
def func(): x = "Python" s = "test" print(x) print(s) s = "Tutorialspoint" print(s) func() print(x)
In above program- x is a local variable whereas s is a global variable, we can access the local variable only within the function it is defined (func() above) and trying to call local variable outside its scope(func()) will through an Error as shown below −
Python test Tutorialspoint Traceback (most recent call last): File "main.py", line 9, in <module> print(x) NameError: name 'x' is not defined
However, we can call global variable anywhere in the program including functions (func()) defined in the program.
Local variables can only be reached within their scope(like func() above). Like in below program- there are two local variables – x and y.
def sum(x,y): sum = x + y return sum print(sum(5, 10))
The variables x and y will only work/used inside the function sum() and they don’t exist outside of the function. So trying to use local variable outside their scope, might through NameError. So obviously below line will not work.
File "main.py", line 2 sum = x + y ^ IndentationError: expected an indented block
A global variable can be used anywhere in the program as its scope is the entire program. Let’s understand global variable with a very simple example −
z = 25 def func(): global z print(z) z=20 func() print(z)
A calling func(), the global variable value is changed for the entire program. Below example shows a combination of local and global variables and function parameters −
def func(x, y): global a a = 45 x,y = y,x b = 33 b = 17 c = 100 print(a,b,x,y) a,b,x,y = 3,15,3,4 func(9,81) print (a)
45 17 81 9 3