Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to use a global variable in a Python function?

I have the following code

k = “I like green tea”
def foo():
     pass

How can I access the global variable inside and outside the function?


1 Answer
Rajendra Dharmkar

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
foo()
print k #accessing global variable outside function
 

OUTPUT

C:/Users/TutorialsPoint1/~.py
I like green tea
I like green tea
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.