-3

I am having issues with values being returned exactly as they are passed to a method despite being modified inside the method.

def test(value):
    value+=1
    return value

value = 0
while True:
    test(value)
    print(value)

This stripped-down example simply returns zero every time instead of increasing integers as one might expect. Why is this, and how can I fix it?

I am not asking how the return statement works/what is does, just why my value isn't updating.

Johnny Dollard
  • 708
  • 3
  • 11
  • 26
  • I updated it to differentiate the question. – Johnny Dollard May 27 '17 at 21:19
  • "I am not asking how the return statement works/what is does, just why my value isn't updating." But the reason your value isn't updating, is because of what the return statement does, and the fact that it doesn't work the way you think it does. – Karl Knechtel Jan 03 '23 at 00:32

2 Answers2

3

You need to assign the return'd value back

value = test(value)
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
-1

Use this :-

def test(value):
  value+=1
  return value

value = 0
while True:
  print(test(value))

You weren't using the returned value and using the test(value) inside the print statement saves you from creating another variable.

  • That still will not increase his integer. – fuglede May 27 '17 at 21:24
  • it won't retain the updated result for reuse in other locations but for testing purpose he/she could use the print statement/simply just assign it to the variable "value" for usability purpose. Moreover, he/she didn't end the while loop so it's infinite execution. – kartik.behl May 27 '17 at 21:34