Reputation: 43
def chan(ref, let, mode):
if mode[0]=="d":
ref=-ref
a=ord(let)
a=a+ref
let=chr(a)
return let
ref=1
let="q"
chan(ref, let,"k")
print(let)
When I run this it comes out with "q" when i want it to come out with "r" What have I done wrong and what do I need to do to make it work?
Upvotes: 0
Views: 73
Reputation: 2960
When you pass in a variable to a python function, it passes a copy of a pointer to the same memory location as the function argument that was passed into the function. What this means is that if you change properties on an object passed to a function, those changes persist (provided the object is mutable) outside the function. But re-assigning that pointer inside the function does not affect the argument outside of the function, as you are simply pointing that pointer copy (inside the function) to a different piece of memory, which does not affect the original variable. Python does neither pass by value nor pass by reference in the sense that other languages do this. There are many articles detailing this, such as:
http://stupidpythonideas.blogspot.com/2013/11/does-python-pass-by-value-or-by.html
So the code above does not change let as you are modifying a copy of the let pointer inside the function, not changing the original pointer itself.
Upvotes: 0
Reputation: 1121914
You need to assign the return value of the chan()
function back to the let
variable:
let = chan(ref, let,"k")
Upvotes: 6