Reputation: 35
I'm new to python and having trouble wrapping my head around what's going wrong here.
Putting this function into python shell:
def add1(x):
x += 1
and when I set p = 0 and call
add1(p)
I get p = 0 still. What gives?
Ultimately I'm trying to make a 'deal' function that adds two random cards to a hand. Would I be calling this with deal(player1_hand)?
Upvotes: 1
Views: 83
Reputation: 1486
All answers here has return statement and it is probably simpliest solution. The thing you probably want is pass by reference which is possible in languages like C# C++ etc. but not here for imuttable integer
You can achieve it by putting your integer value in your own class because instances of classes are passed by reference and then you can change integer value without return statement.
Example:
class IntHolder:
def __init__(self):
self.value = 0
def add1(x):
x.value += 1
myInt = IntHolder()
add1(myInt)
print(myInt.value)
Output:
1
You can also write your own class which gives you muttable integer.
Upvotes: 1
Reputation: 195
What you're missing here is to understand the scope of variables. In Python (like in most programming languages), entering a function means you're entering a new scope, in which only the function's arguments, plus any global variables, are available.
When leaving the function, this scope (and any changes made to the variables in that scope) disappears. This is why you get this:
def add1(x):
x += 1
p = 0
add1(p)
print(p)
Will still show 0
.
The best and cleanest option here is to make your function return the new value. This way the function is what is called a "pure" function in that it operates only on its arguments, and produces a new value, without depending or affecting the global scope:
def add1(x):
return x + 1
p = 0
p = add1(p)
print(p)
For more info, you can read up https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime
Hope this helps!
Upvotes: 3
Reputation: 348
In the above program, you are copying the reference of variable p to local variable x. Hence you must return the value of x to p again.
def add1(x):
return x+=1
p = add1(p)
Upvotes: 0
Reputation: 776
def add1(x):
return x+=1
p = add1(p)
Mutating p
inside function without return would require you making p
global.
But there is more to it, have a look at this question How do I pass a variable by reference?
Upvotes: 1
Reputation: 7268
You have to return updated value:
def add1(x):
x += 1
return x
p = 0
print (add1(p))
Upvotes: 0