473,408 Members | 1,749 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

How does one write a function that increments a number?

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


Thanks in advance,
Vaibhav

Jul 19 '05 #1
10 15598
Hi, please refer to the sections about the augments passing in Python
tutorial. Python’s pass-by-assignment scheme isn’t the sameas
C++’s reference parameters, but it turns out to be very similar to
C’s arguments in practice:
 Immutable arguments act like C's "by value" mode. Objects such as
integers and strings are passed by object reference (assignment), but
since you can't change immutable objects in place anyhow, the effect is
much like making a copy.
 Mutable arguments act like C's "by pointer" mode. Objects such as
lists and dictionaries are passed by object reference, which is similar
to the way C passes arrays as pointers—mutable objects can be changed
in place in the function, much like C arrays.

Let’s have a try:
def incr(counters): counters[0] += 1

counters =[100]
incr(counters)
print counters [101]


Jul 19 '05 #2
Wait... so this means it is impossible to write a function that
increments an integer without turning the integer into a list?

Jul 19 '05 #3
<an***********@gmail.com> wrote:
Wait... so this means it is impossible to write a function that
increments an integer without turning the integer into a list?


The short answer is no you can't, because integers are immutable (as
well as floats and strings among others). The longer answer is you can
create a, say, MutableInt class whose instances behave as modifiable
integers. Most probably you don't really need this, but if you think
you do, others in the list will sketch out how.

George

Jul 19 '05 #4
an***********@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
Jul 19 '05 #5
an***********@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
Jul 19 '05 #6
Thank you all for your helpful replies.
Regards,
Vaibhav

Jul 19 '05 #7
On Fri, 24 Jun 2005 21:53:03 -0700, an***********@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:

counter = 1
counter += 1
print counter
--
Steven
Jul 19 '05 #8
Sun, 26 Jun 2005 04:14:19 +1000 skrev Steven D'Aprano:
On Fri, 24 Jun 2005 21:53:03 -0700, an***********@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.
Jul 19 '05 #9
On 24 Jun 2005 22:41:00 -0700, "an***********@gmail.com"
<an***********@gmail.com> declaimed the following in comp.lang.python:
Wait... so this means it is impossible to write a function that
increments an integer without turning the integer into a list?
In older languages, a function is defined as subprogram which
returns a value on invocation (and side-effects -- that is, changes in
the values of input arguments -- are frowned upon). A
subroutine/procedure, OTOH, does not return a value and side-effects are
expected.

The simplest way to look at Python is that it is all "functions"
and one should not expect to change arguments (I'm ignoring the matter
of lists and dictionaries, where one is changing the contents of the
list/dictionary, but not the dictionary itself, per se).

So the full definition of your increment requires the usage...

def incr(x):
return x + 1

a = 4
a = incr(a)

Python "def"s that don't have an explicit "return" still return
a value -- "None"
def incr(x): .... x = x + 1
.... a = 4
print incr(a) None def incr(x): .... return x + 1
.... print incr(a) 5

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #10
On Sat, 25 Jun 2005 19:31:04 +0000 (UTC), Mandus <ma****@gmail.com>
declaimed the following in comp.lang.python:
it's because python do call by value, not by reference for such simple
variables.
Not correct...

Python passes the reference to the argument... But the
assignment inside the function, as with all Python assignments, defines
a new association -- the argument "name" is now pointing to some /other/
object.
def incr(x): .... print id(x)
.... x = x + 1
.... print id(x)
.... a = 3
print id(a) 3307128 incr(a) 3307128
3307116


Note how the first id(x) has the same integer object as 'a'...
but after the assignment, id(x) is something else.

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Melissa | last post by:
I'm trying to create a function that I can put in a query field that will consecutively number the records returned by the query starting at 1 and will start at 1 each time the query is run. So far...
6
by: Bore Biko | last post by:
I don't know hopw to do this, like "printf", or "sprintf", I know they use a stack but how to make my own...?? Thanks in advance !! robert.bralic@si.t-com.hr
3
by: ad | last post by:
I download the source of Portal Starter Kit form http://www.asp.net/Default.aspx?tabindex=8&tabid=47 I find there are Register tag in many .aspx, like this HtmlModule.ascx , the first line is ...
12
by: Sheldon | last post by:
#define UWORD2 unsigned short int typedef BYTE Boolean; Boolean evaluateBit(UWORD2 *value, int bitnumber); Boolean evaluateBit(UWORD2 *value, int bitnumber) { int one=1; return (one &(*value...
1
by: Tony B | last post by:
Hi, I'm trying to understand a small cpp program which uses a function called write. An example of a line using this function is write (hsocket,strclose,strlen(strclose)); where strclose is a...
4
by: ajmastrean | last post by:
I cannot get any (hex) number in the "0x80"-"0x89" range (inclusive) to write properly to a file. Any number in this range magically transforms itself into "0x3F". For instance, debugging shows...
5
by: Immortal Nephi | last post by:
I would like to design an object using class. How can this class contain 10 member functions. Put 10 member functions into member function pointer array. One member function uses switch to call...
2
by: Samant.Trupti | last post by:
Hi, Does main function support unicode? int main( int argc, char** argv ) can I say int mainw( int argc, wchar_t** argv )? Thanks Trupti
4
by: TuRu87 | last post by:
Hello, So I'm trying to create a malloc function and want to print some addresses to check on them and be able to visualize a little what's going on but I can't use printf cause it messes around...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.