Keep variable value in a python function

1

Within a function I have a cumulative variable, and I call this function over and over, the problem that it loses values every time it enters. Summarizing 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()

output is:

I would like to keep the value of a, and the output in this case be incremented.

    
asked by anonymous 09.06.2016 / 22:24

1 answer

3

Python does not have a method of declaring static variables, but there are a few ways to do that.

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()
    
10.06.2016 / 01:11