Leo
Leo

Reputation: 109

Python3: Multiple global vars

I'm working with global vars but I get the error "NameError: name 'second_global_var' is not defined"

def my_function():
    global first_global_var, second_global_var
    if(first_global_var or second_global_var):
        pass

Why it shows the error for 'second_global_var' and not for 'first_global_var', even if I define them each one with in its own line with global, the error persist for the variable 'second_global_var'.

Upvotes: 2

Views: 2881

Answers (2)

kolonel
kolonel

Reputation: 1432

Inside the interpreter, you have:

   >>> def my_function():
    ...     global first_global_var, second_global_var
    ...     if(first_global_var or second_global_var):
    ...         pass
    ... 

Then calling the function:

>>> my_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in my_function
NameError: global name 'first_global_var' is not defined

It complains about the first variable that it is not defined.

Upvotes: 0

Kevin
Kevin

Reputation: 30171

The global statement does not create variables. It just makes Python look for them in the global namespace instead of the local namespace. In other words, saying global some_name tells Python to look for a global variable called some_name whenever you try to refer to some_name.

If that variable doesn't exist when you try to use it, Python will raise a NameError.

Upvotes: 2

Related Questions