Today we will learn on this article Global vs Local Variables in Python. Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can only be accessed inside the function in which they are declared, whereas global variables can be accessed throughout the function. When you call a function, the variables declared inside it are fetched.
#!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total
Result
Inside the function local total : 30 Outside the function global total : 0