Python method not returning value

Question:

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.

Asked By: Johnny Dollard

||

Answers:

You need to assign the return‘d value back

value = test(value)
Answered By: Cory Kramer

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.

Answered By: kartik.behl
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.