In general, a variable that is defined in a block is ailable in that block only. It is not accessible outside the block. Such a variable is called a local variable. Formal argument identifiers also behe as local variables.
The following example will underline this point. An attempt to print a local variable outside its scope will raise the NameError exception.
Example: Local Variabledef greet(): name = 'Steve' print('Hello ', name) greet() print(name) #NameErrorTry itHere, name is a local variable for the greet() function and is not accessible outside of it.
Any variable present outside any function block is called a global variable. Its value is accessible from inside any function. In the following example, the name variable is initialized before the function definition. Hence, it is a global variable.
Example: Global Variablename='John' def greet(): print ("Hello ", name) greet() print(name)Try itHere, you can access the global variable name because it has been defined out of a function.
However, if we assign another value to a globally declared variable inside the function, a new local variable is created in the function's namespace. This assignment will not alter the value of the global variable. For example:
Example: Local and Global Variablesname = 'Steve' def greet(): name = 'Bill' print('Hello ', name) #Hello Bill greet() print(name) #steveTry itNow, changing the value of global variable name inside a function will not affect its global value.
If you need to access and change the value of the global variable from within a function, this permission is granted by the global keyword.
Example: Access Global Variablesname = 'Steve' def greet(): global name name = 'Bill' print('Hello ', name) greet() print(name) #BillTry itThe above would display the following output in the Python shell.
It is also possible to use a global and local variable with the same name simultaneously. Built-in function globals() returns a dictionary object of all global variables and their respective values. Using the name of the variable as a key, its value can be accessed and modified.
Example: Global Variablesname = 'Steve' def greet(): globals()['name'] = 'Ram' name='Steve' print ('Hello ', name) greet() print(name) #RamTry itThe result of the above code shows a conflict between the global and local variables with the same name and how it is resolved.
Visit Globals and Locals in Python for more information.