[Tutor] changing name value with function return

Dave Angel d at davea.name
Tue Oct 30 19:26:04 CET 2012

On 10/30/2012 12:56 PM, richard kappler wrote:
> If I have a variable and send it's value to a function to be modified and
> returned, how do I get the function return to replace the original value of
> the variable?
> Example:
> import random
> x = 50
> def rndDelta(x):
>     d = random.uniform(-10, 10)
>     x = x + d
>     return x
> When I call rndDelta, it functions as intended, I get a return that is x
> adjusted by some random value. This, however, I know does not actually
> change x. Let's say I call randDelta(x) and it returns 42.098734087, if I
> then type x, I still get 50. I want x to now be 42.098734087.
> regards, Richard

There are two normal ways that a function may modify values in a calling
function.  One is to modify mutable arguments, and the other is to
return a value.  It's considered bad practice to do both in the same
function.  Anyway, since the int object is immutable, only the latter
choice is available.

Once you return a value, it's thrown away unless the caller does
something with it.  Quite common is to assign it somewhere.  In your
case, you want it to replace the original value of x, so:

def test():
    val = 50
    val = rndDelta(val)

When you use the same name x for both variables, you just confuse
things.  They are not the same thing at all, so I gave them different
names.  Once you're experienced enough to always know which ones
correspond, then you might decide to reuse names.

Notice that there's not really a variable val.  There's a name val,
which is bound to an int object =50 at first, then rebound to a
different object, float object 42.09 whatever.  We call var a variable,
but the word has a different meaning than in most other languages.



More information about the Tutor mailing list