0

In python I wrote:

registered_to = 0

def execute_data():
    registered_to += response.text.count("<div class=\"info-msg\">")

But I'm getting:

registered_to += response.text.count("<div class=\"info-msg\">")
UnboundLocalError: local variable 'registered_to' referenced before assignment
flaxel
  • 4,173
  • 4
  • 17
  • 30
  • Has your problem been solved? If yes, then please accept the answer by click on the tick mark icon just below the vote counter – user12137152 Jan 17 '21 at 09:20
  • Thanks for accepting the answer, have you understood the problem? – user12137152 Jan 17 '21 at 09:29
  • 1
    Does this answer your question? [How to change a global variable from within a function?](https://stackoverflow.com/questions/41369408/how-to-change-a-global-variable-from-within-a-function) – Jolbas Jan 17 '21 at 10:38

1 Answers1

0

Is this what you want?

registered_to = 0

def execute_data():
    global registered_to
    registered_to += response.text.count("<div class=\"info-msg\">")

global keyword must be used whenever you wish to modify/create global variables from a non-global scope like a function. If you are just using a global variable from a non-global scope and not modifying it, you need not use the keyword.

Examples

  1. Using global variable in a non-global scope but not modifying it
wish = "Hello "

def fun():
    print(wish)

fun()
  1. Using global variable in a non-global scope and modifying it as well
wish = "Hello "

def fun():
    word += "World"
    print(wish)

fun()
user12137152
  • 732
  • 1
  • 5
  • 14
  • why u defined it twice? it's already outside function –  Jan 17 '21 at 08:59
  • I want it to be global 0 and the function every time adds to it (and when it ends its value is always saved), your code won't do that –  Jan 17 '21 at 09:00
  • Check this : https://www.geeksforgeeks.org/global-keyword-in-python/ – user12137152 Jan 17 '21 at 09:03
  • they did the same as I did in example 1 –  Jan 17 '21 at 09:05
  • This is also useful : https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – user12137152 Jan 17 '21 at 09:06
  • @martin for modification of a global variable, you need to use global keyword. In the first example, they are just using it and not modifying it. See the 2nd example where they are modifying a globally declared variable in a function which has a local scope. – user12137152 Jan 17 '21 at 09:10