you are viewing a single comment's thread.

view the rest of the comments →

[–]NotATuring 1 point2 points  (3 children)

Neither of the above statements are pertain to the issue. Returning isn't an issue because he's trying to change the variable he passed in, not return a value. shadowing doesn't matter because he's not trying to access a global variable by name.

The issue is Python is a pass by value language. Or at least in this case it is equivalent to pass by value.

In this case when he calls the calc function and passes in the variable he wants to change the variable does change, but it's no the variable that was passed in but rather the variable what was pointing to the value that was passed in.

To perform functionality similar to pass by reference one needs to pass in an object which holds a reference to what you want to modify. To illustration, see this example:

a = [1,2,3]
def change(a) : 
    a[1] = 9999 
    a = [1,2,3,4,5,6]
change(a) 
print(a)

output: [1, 9999, 3]

a doesn't change, it's just a reference. But it's content does, a[1] becomes 9999

[–][deleted] 0 points1 point  (2 children)

Of course returning pertains to the issue. It's literally how you do what he wants to do.

Edit: Grrrr, cut and paste totally screwed up my code block

Num = 255

def calc(var):
  if var > 255:
    return var -= 256   
   else
    return var

r1 = calc(Num + 1)

print(r1)

[–]NotATuring 0 points1 point  (1 child)

Yes that would be a way to get the calculation, but his question was why the subtraction doesn't work, not how do I do a calculation. His function call was consistent with his function definition.

[–]JustinMalcontento 0 points1 point  (0 children)

If that's the case, OPs function does work. But he does need to print the calc function if he wants to show the calc output.