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.


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


I like green tea
I like green tea
Updated on 13-Feb-2020 05:53:19