Python Forum

Full Version: auto increment
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
num=1000
def inc():
    increment = num + 1
     return inc


print(inc())
in inc function the number 1000 is incremented by one and it is giving 1001 .when function is called again it is giving the same value 1001.what should be changed so that on every call to the function the value should increment by one and values like 1001,1002,1003............
Hello, next time when posting code, please use Python code tags (you can find help here).
increment = num + 1
This line only changes variable increment, instead you want to change num.
return inc
With this code, function returns itself, and not a value you want.
How about...

num = 1000

def inc():
    global num
    num += 1
    return num

for x in range(10):
    print(inc())
You don't need a global variable
$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def generate_incrementer(start):
...     num = start
...     def incrementer():
...         nonlocal num
...         num += 1
...         return num
...     return incrementer
... 
>>> incrementer = generate_incrementer(999)
>>> print(incrementer())
1000
>>> print(incrementer())
1001
In fact, I wouldn't make incrementer global unless you really need it to be.

And if you don't actually need a function to do it, you can use a built-in
>>> from itertools import count
>>> counter = count(1000)
>>> next(counter)
1000
>>> next(counter)
1001
If you can tell us your larger goal we might be able to provide a better way, still.
Or a class! (and my axe!)
>>> class counter:
...   def __init__(self, initial=0):
...     self.value = initial
...   def inc(self, increment_by=1):
...     self.value += increment_by
...     return self.value
...   def __call__(self):
...     return self.inc()
...
>>> inc = counter(1000)
>>> for _ in range(10):
...   print(inc())
...
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
It's probably all the functional programming I've been doing that has me thinking in terms of closures :)
In all seriousness though, a closure is just a class with less steps lol
I would name the class Counter.