How does one write a function that increments a number?
Brian van den Broek
bvande at po-box.mcgill.ca
Sat Jun 25 02:17:51 EDT 2005
anonymousnerd at gmail.com said unto the world upon 25/06/2005 01:41:
> Wait... so this means it is impossible to write a function that
> increments an integer without turning the integer into a list?
>
Well, one of these options will probably suit:
>>> def increment_counter(data):
... data += 1
... return data
...
>>> counter = 0
>>> counter = increment_counter(counter)
>>> counter
1
Or, if you only care about one counter, don't like the
return/assignment form, and don't mind all the cool kids frowning on
the use of global:
>>> counter = 0
>>> def increment_counter():
... global counter
... counter += 1
...
>>> counter
0
>>> increment_counter()
>>> counter
1
>>>
Nicest might be using a class, where you keep a clean namespace, and
don't have the return/assignment form:
>>> class My_class(object):
... def __init__(self):
... self.counter = 0
... def increment_counter(self):
... self.counter += 1
...
>>> my_object = My_class()
>>> my_object.counter
0
>>> my_object.increment_counter()
>>> my_object.counter
1
>>>
This also lets you have multiple independent counters:
>>> my_other_object = My_class()
>>> my_other_object.counter
0
>>> my_other_object.increment_counter()
>>> my_other_object.increment_counter()
>>> my_other_object.counter
2
>>> my_object.counter
1
>>>
Best,
Brian vdB
More information about the Python-list
mailing list