Variables are nothing but memory locations reserved by python to store values. A variable in python can be created simply as var = 10. Python Provides us the facility not to define the type of the variables being used. That is in many other high level language we have to define
Int var =10 #define a int variable
Python has the capability to identify the type of the data being saved and reserves memory based on that. Hence by assigning different data types to variables, you can store integers, decimals or characters in these variables.
Global Variables
A variable declared outside of the function or in a global scope is called a Global variable. This variable can be accessed inside or outside of the function.
A simple example include,
jagadishm@: cat variables.py
#!/usr/bin/python
x = "global"
def fun():
print "x inside function",x
fun()
print "x Outside Function",x
When we execute the function, we can see the same value from inside the function and also outside as below,
jagadishm@: python variables.py
x inside function global
x Outside Function global
The global variable x is defined outside of the function and in global scope and hence it can be accessed by everything in that code.
Changing a Global variable -If we try to change the global variable inside a function like below,
#!/usr/bin/python
x = "global"
print x * 2
def fun():
print "x inside function",x
x = x * 2
fun()
print "x Outside Function",x
The first variable change ( x * 2) which display “globalglobal” but the same value change inside a function will result in below error,
UnboundLocalError: local variable 'x' referenced before assignment
Local Variable - A Local variable is declared inside a function body or within local scope as below,
#!/usr/bin/python
def foo():
y = "local"
foo()
print(y)
If we run the code, we see an error as below
NameError: name 'y' is not defined
Since the variable y is of local scope and defined inside a function, we cant access that outside the function.
Global and Local variable in same Code - Global and local variable can both be defined inside the code as below,
#!/usr/bin/python
x = "global "
def fun():
global x
y = "local"
x = x * 2
print(x)
print(y)
fun()
The global variable can be used inside a function by defining the same variable “x” with a global keyword.
Non-Local variable - Python 3 provides a nonlocal keyword. Non local variables are used in nested functions whose scope is not defined. This means the variable can be neither in the local or global scope.
No comments :
Post a Comment