0

Hey guys just a quick and simple question. I have a function in which I need to add numbers per action. I have already written a script however, it resets to 0 every time. I already know that the mistake is declaring 0 every time however I do not know how to fix this. ~ Here is an example to help:

valid = 0
connection_error = 0
def seesite():
  global valid
  global connection_error
  valid = 0
  connection_error = 0
  try:
    requests.get("https://google.com")
    valid += 1
    print(f"Valid requests: {valid}")
  except:
    error += 1
    print(f"Invalid requests: {invalid}")

~ I would like to conduct this however without resetting the value. Any ideas?

xnarf
  • 100
  • 9

1 Answers1

1

Use numfunc.value and define numfunc.value after the function definition. This emulates static function variables:

def numfunc():
    print(numfunc.value)
    numfunc.value += 1
numfunc.value = 0

numfunc() # 0
numfunc() # 1

Note that this has no real advantage over global variables, though. It just puts the variable into the namespace of the function instead of the global namespace, with the same accessibility (since there is no "private" or "protected" in Python).

Jan Christoph Terasa
  • 5,781
  • 24
  • 34