I am trying to write a python function that on the first call, returns a 1. On the second call, returns a 2. On the third, a 3. Etc.
Currently, I have achieved this using a global variable:
index = 0
def foo():
global index
index += 1
return index
When calling the function three times:
print(foo())
print(foo())
print(foo())
It returns the values expected:
1
2
3
But, I've read that it is bad practice to use global variables. So, I was wondering if the same result could be achieved without using globals.
Any suggestion?
Thank you for your help.
next(inc); next(inc)
instead ofinc.next()
because the former works in python2.6+ and also in python3, while the latter only works in python2.x – Wyandotte