Q:

How can I define a global variable in a function?

I have a file, f.py:
def func():
    if 'x' not in globals():
        setattr(f, 'x', 0)
    global x
    x += 10
    print x

I am in an interactive session:
>>> import f
>>> f.func()
Traceback (most recent call last):
[...]
NameError: global name 'x' is not defined

How should I modify func to define x if it is not already defined?

A:

def func():
    global x

    if 'x' not in globals():
        x = 0

    x += 10

    print(x)

