0

I'm using Pycharm and gives me this error whenever I try to run the code: NameError: name 'answer' is not defined. Below is the problematic code.

array = []
while integer:
    integer, value = divmod(integer, (int(target_system.get())))
    array.append(VA2SY[value])
    global answer
    answer = (''.join(reversed(array)))

print(end)
messagebox.showinfo("Eredmény:", answer)
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61
B. Daniel
  • 13
  • 6
  • My research has led me to believe that this is a bug in PyCharm but I'm not sure. – B. Daniel Dec 10 '17 at 15:15
  • 2
    Maybe it's Pycharm way to make sure that the users can't use global variables :) – Huy Vo Dec 10 '17 at 15:18
  • What happens if you comment out `global answer`? – dkato Dec 10 '17 at 15:20
  • What is the initial value of `integer`? If it's zero (or other 'falsy' value), the loop will never execute, and therefore no value ever gets assigned to `answer`. – jasonharper Dec 10 '17 at 15:41
  • The "answer" variable being global doesn't make any difference, it's just a leftover from previous tries, if I leave it as a "normal" variable then I get the same error. And i'm sure this is the code that causes the problem. – B. Daniel Dec 11 '17 at 17:05
  • You should ask your question more precisely... You can also get such a NameError if you use a class before you defined it. – clfaster Dec 11 '17 at 17:11

1 Answers1

0

Here is a short example of how to use a global variable in python.

Example:

If you want to use global_answer in somefunc, you need to tell python that global_answer is a global variable.

def somefunc():
    # mark global_answer as global variable
    global global_answer
    while global_answer is "global":
        global_answer = "Will show"
        # not_global is a local variable
        not_global = "Will not show"


# Declare variable
global_answer = "global"
not_global = "not global"
somefunc()
print("Global:", global_answer)
print("Not Global:", not_global)

Error Reproduction

I achieve the same error message with that code:

def somefunc():
    while global_answer is "global":
        global global_answer          # Line moved
        global_answer = "Will show"


# Declare variable
global_answer = "global"
somefunc()

Possible Solution

Move your code line global answer to the first line of your method.

Check if you defined all your classes before you use them, else you can also end up with a NameError. more details

The error might be outside of the code you provided. Where do you declare the global variable answer?

clfaster
  • 1,450
  • 19
  • 26
  • The "answer" variable being global doesn't make any difference, it's just a leftover from previous tries, if I leave it as a "normal" variable then I get the same error. And i'm sure this is the code that causes the problem. – B. Daniel Dec 11 '17 at 17:05