How does one write a function that increments a number?

Mandus mandus at gmail.com
Sat Jun 25 21:31:04 CEST 2005


Sun, 26 Jun 2005 04:14:19 +1000 skrev Steven D'Aprano:
> On Fri, 24 Jun 2005 21:53:03 -0700, 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
>
> Why does it need to be a function? Why complicate matters? Isn't it
> simpler to just do this:
[snip]

I guess he have some reason for it...

it's because python do call by value, not by reference for such simple
variables. 

If you absolutely want to do this, you can try:

def incr(counter):
   counter[0] += 1

counter=[1]
incr(counter)
print counter[0]

But I agree with Steven, this is probably not what you want to do :)

-- 
Mandus - the only mandus around.



More information about the Python-list mailing list