Is there a way to keep a global throughout multiple def statements?

Recommended Answers

All 2 Replies

global variables are available everywhere after their definiton in a module (and outside the module can be qualified by the module name)

For clarification:
Global variable is defined by giving it a value at zero indentation level in the .py file.
For example in the following code globalvar is printed.

globvar=None

def some_function():
    print globalvar

There is a distinction if you want to change the value of the variable or just read it.

for example in the following code "something" is printed.

globalvar="something"

def somefunt():
    globalvar="something else"

somefunt()
print globalvar

To make the function modify the globalvar:

globalvar="something"

def somefunt():
    global globalvar
    globalvar="something else"

somefunt()
print globalvar

Note: The changing means to change to object that is labelled by the global variable.

For example

globalvar=[1]
def somefunt():
        globalvar.append(2)

somefunt()
print globalvar

#prints [1,2]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.