How to use a global variable in a Python function?

PythonServer Side ProgrammingProgramming

The terms, global and local correspond to a variable's reach within a script or program. A global variable is one that can be accessed anywhere. A local variable can be accessed only within its frame. A local variable cannot be accessed globally.

Global variables are the one that are defined and declared outside a function and can be used anywhere.

If a variable with same name is defined inside the scope of a function then it will print the value given inside the function only and not the global value.

The given code is re-written to show how the global variable is accessed both inside and outside the function foo.

Example

# This function uses global variable k
k = "I like green tea"
def foo():
    print k #accessing global variable inside function
foo()
print k #accessing global variable outside function
 

Output

C:/Users/TutorialsPoint1/~.py
I like green tea
I like green tea
raja
Published on 07-Dec-2017 10:19:28
Advertisements