How does one write a function that increments a number?

Discussion in 'Python' started by anonymousnerd@gmail.com, Jun 25, 2005.

  1. Guest

    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
     
    , Jun 25, 2005
    #1
    1. Advertising

  2. Guest

    Hi, please refer to the sections about the augments passing in Python
    tutorial. Python’s pass-by-assignment scheme isn’t the same as
    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]
    >>>
     
    , Jun 25, 2005
    #2
    1. Advertising

  3. Guest

    Wait... so this means it is impossible to write a function that
    increments an integer without turning the integer into a list?
     
    , Jun 25, 2005
    #3
  4. <> 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
     
    George Sakkis, Jun 25, 2005
    #4
  5. 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
     
    Brian van den Broek, Jun 25, 2005
    #5
  6. 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
     
    Steven Bethard, Jun 25, 2005
    #6
  7. Guest

    Thank you all for your helpful replies.
    Regards,
    Vaibhav
     
    , Jun 25, 2005
    #7
  8. On Fri, 24 Jun 2005 21:53:03 -0700, 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
     
    Steven D'Aprano, Jun 25, 2005
    #8
  9. Mandus Guest

    Sun, 26 Jun 2005 04:14:19 +1000 skrev Steven D'Aprano:
    > On Fri, 24 Jun 2005 21:53:03 -0700, 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.
     
    Mandus, Jun 25, 2005
    #9
  10. On 24 Jun 2005 22:41:00 -0700, ""
    <> 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
    >>>

    --
    > ============================================================== <
    > | Wulfraed Dennis Lee Bieber KD6MOG <
    > | Bestiaria Support Staff <
    > ============================================================== <
    > Home Page: <http://www.dm.net/~wulfraed/> <
    > Overflow Page: <http://wlfraed.home.netcom.com/> <
     
    Dennis Lee Bieber, Jun 26, 2005
    #10
  11. On Sat, 25 Jun 2005 19:31:04 +0000 (UTC), Mandus <>
    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.

    --
    > ============================================================== <
    > | Wulfraed Dennis Lee Bieber KD6MOG <
    > | Bestiaria Support Staff <
    > ============================================================== <
    > Home Page: <http://www.dm.net/~wulfraed/> <
    > Overflow Page: <http://wlfraed.home.netcom.com/> <
     
    Dennis Lee Bieber, Jun 26, 2005
    #11
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nicolla MacPherson
    Replies:
    4
    Views:
    402
    Karl Heinz Buchegger
    Aug 13, 2003
  2. 4ward.com

    Loop with float increments (frange)?

    4ward.com, Apr 14, 2006, in forum: Python
    Replies:
    3
    Views:
    465
    Tim Peters
    Apr 14, 2006
  3. M
    Replies:
    6
    Views:
    378
  4. Richard

    UDB and pointer increments and decrements

    Richard, Sep 23, 2008, in forum: C Programming
    Replies:
    10
    Views:
    483
    Tim Rentsch
    Oct 9, 2008
  5. Steve Schuler
    Replies:
    1
    Views:
    141
    Sean Kelly
    Aug 12, 2003
Loading...

Share This Page