How does one write a function that increments a number?

Steven Bethard steven.bethard at gmail.com
Sat Jun 25 02:25:54 EDT 2005


anonymousnerd at gmail.com wrote:
>   Apologies if this question seems stupid: How does one write a
> function that increments a value in Python? When I tried, the variable
> never changed.
> The session went like this:
> 
>>>>def incr(counter):
> 	counter = int(counter)
> 	counter += 1
> 
>>>>counter = 1
>>>>incr(counter)
>>>>print counter
> 1

You probably don't really want to write code like this in Python.  How 
about:

class Counter(object):
     def __init__(self, start=0):
         self.value = start
     def incr(self):
         self.value += 1

counter = Counter(1)
counter.incr()
print counter.value

Or you can likely get everything you need from itertools.count.

STeVe



More information about the Python-list mailing list