Rolling Happy
Rolling Happy

Reputation: 3

NameError: name 'a' is not defined... gives this error even after I have converted variable to global

I'm getting this error and am not able to find any proper reason or solution it

def change_a():
    global a
    for i in ['O','X']:
        if not(i==a):
            a=i
            break

The purpose of this code is to switch between X and O.

the output I get is:

NameError: name 'a' is not defined.

I'm running this in Python 3.9.0

Upvotes: 0

Views: 1030

Answers (2)

user3980558
user3980558

Reputation:

At the time of the comparison (i==a) the variable a is not yet defined. Therefore, you need to provide a with a value before that. In addition, as Shannarra mentioned, you can switch the variable between the two characters:

a = 'X'

def change_a():
    global a
    a = 'O' if a == 'X' else 'O'
    print(a)
change_a()

Output:

O

Also, note that using global variables is considered bad practice as they enable functions to have hidden (non-obvious, surprising, hard to detect and diagnose) side effects, leading to an increase in complexity, potentially leading to spaghetti code.

Upvotes: 1

Shannarra
Shannarra

Reputation: 559

If you want to just switch the variable between those two characters you can:

a = 'O' if a == 'X' else 'X'

No need for the function, the loop or the global variable.

Upvotes: 0

Related Questions