-1

So I wrote this fragment of code inside one of my projects, and defined n to be a boolean value True. Then, I used it to make a toggle case of a pause/resume button. For some reason, I get the error for using n in the if statement before allegedly assigning it inside the if and else code, although I already assigned it above the whole function.

Can somebody explain this error? And maybe suggest a way to fix it?

n = True

    def pauseresume():
        if n:
            pauseb.configure(text="Resume")
            n = False
        else:
            pauseb.configure(text="Pause")
            n = True
  • 1
    It's a scope problem. `pauseresume` needs to explicitely use `global n`, or have it as argument. – crissal Jun 24 '21 at 09:48
  • either pass it in the function or declare it as a global var. – DirtyBit Jun 24 '21 at 09:49
  • 1
    Does this answer your question? [Using global variables in a function](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function) – umläute Jun 24 '21 at 09:53
  • Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – mkrieger1 Jun 24 '21 at 09:54

2 Answers2

0

If you want to use a global variable, you need to explicitely use it via global keyword.

n = True

def pauseresume():
  global n
  pauseb.configure(text="Resume" if n else "Pause")
  n = not n  # switch to other bool value
crissal
  • 2,547
  • 7
  • 25
0

You can not use global var in a function solution:

def pauseresume():
    global n

    if n:
    ...

For detail, click Using global variables in a function.

sirius9515
  • 309
  • 1
  • 8