-4

I tried to reference a global variable in a function where it was defined outside of the function. The variable was made global and was defined before the function was defined or called.

For example the script looks something like this:

global add
add = 0

def addit():
    print(add)
    add = add + 1
    addit()

addit()

The error in the terminal is that the variable (add in this example) is referenced before its assignment. I have searched online for help but I have not been able to figure it out.

  • The `global` statement has to be *inside* the function that contains an assignment to the variable (since that would otherwise make the variable local). A `global` at top level is utterly pointless, I have no idea why Python even allows that. – jasonharper Dec 19 '22 at 15:21
  • There is no need to use `global` in global scope. A variable created in global scope is already global. The `global` keyword is used inside a function to declare that the variable you want to modify is the one in global scope, otherwise a local variable is created. – Steven Rumbalski Dec 19 '22 at 15:22
  • 1
    @jasonharper Because it's not actively harmful and would complicate the grammar by having a statement that is illegal in a particular scope. (Note that things like `nonlocal`, `break`, and `continue` are not banned by scope, but by the compound statement they must occur within.) – chepner Dec 19 '22 at 15:23

1 Answers1

1

The global keyword needs to be inside of your addit function in order to work:

add = 0

def addit():
    global add
    print(add)
    add += 1
    if (add < 995): addit() # run recursive until error

addit()

Also improvised on the RecursionError.

The Myth
  • 1,090
  • 1
  • 4
  • 16
Wolric
  • 701
  • 1
  • 2
  • 18
  • Well, the whole idea here looks recursion which is what you removed. Why not stop recursion after a certain point? – The Myth Dec 19 '22 at 15:23
  • Of course using a condition to break the recursive calls would work. I removed the line not knowing a possible break condition. – Wolric Dec 19 '22 at 15:27