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?

7
  • That's not valid python. Can you create an example with actual code instead of pseudocode? Commented May 14, 2020 at 5:50
  • Its just an example :) I want to do something like that. Commented May 14, 2020 at 5:51
  • the best way would be to keep track of the total outside the function Commented May 14, 2020 at 5:51
  • And use a global identifier? Commented May 14, 2020 at 5:51
  • Try declaring value as global variable OR retuen value and pass it in function every time. Commented May 14, 2020 at 5:51

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I copied and pasted those exact line into my interpreter, and they are fine.
Yes so sorry! Forgot to add the function identifiers facepalm

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.