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

What is the difference between global and local variables in Python?

In the following code which are the global and local variables

q = "I love coffee"
def f():
    p = "Me Tarzan, You Jane."
    print p
 f()
print q


1 Answer
Rajendra Dharmkar

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.

In the given code

q = "I love coffee" # global variable
def f():
    p = "Me Tarzan, You Jane." # local variable
    print p
 f()
print q

The output is as follows

Me Tarzan, You Jane.
I love coffee

In the given code, p is a local variable, local to the function f(). q is a global variable accessible anywhere in the module.

Advertisements

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