Keep variable value in python function

Asked

Viewed 481 times

1

Within a function I have a cumulative variable, and I call this function over and over again, the problem that it loses values every time it enters. Summing up what I want to do is:

def teste(a):
  a=a+1
  c=7
  print a
  return c


def main():   
 a=1
    for b in range(0,5):
        c=teste(a)
main()

the exit is:

inserir a descrição da imagem aqui

would like to maintain the value of a, and the output in that case be increased.

  • You are with two as in your code: one is the formal parameter of the function and the other is the global variable.

  • this is a simple code to reproduce the idea, in case if it were global it would work, think that the second part is within a function

2 answers

3


Python does not have a method of declaring static variables, but there are some means and do this.

def static_num(): # método com variável estática
    static_num.x += 1 # incremento
    return static_num.x

static_num.x = 0 # inicia variável

if __name__ == '__main__':
    for i in range(10):
        print static_num()

0

Then the error that must, is due to the fact that you are just calling the variable that is in the test function. Without incrementing any value to it, then it will repeat in the lop for. To solve this just add the variable b that is in your for:

   def teste(a):
  a=a+1
  c=7
  print (a)
  return c


def main():   
    a=1
    for b in range(0,5):
        c=teste(a+b)
main()

So it will increase with the variable without mutalá directly.

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.