0

I have a global variable called "result" and trying to change this value by calling a function .

import sys 

def increment_result(a):
    for i in range(0,3):
        a += 1

result = 0
increment_result(result)
print(result)

But the result value is zero but expecting the result value to be 3.How can I change this global variable by using Pass by Reference in Python.

athavan kanapuli
  • 443
  • 5
  • 17

1 Answers1

2

Instead of trying to change global variable, return the changed value and reassign the return value back to the variable from the caller:

import sys 

def increment_result(a):
    for i in range(0,3):
        a += 1
    return a

result = 0
result = increment_result(result)
print(result)

If you really want to change global variable, you need to declare it using global statement:

def increment_result(a):
    global result  # <-- to access the global variable
    for i in range(0,3):
        a += 1
    result = a
falsetru
  • 336,967
  • 57
  • 673
  • 597
  • This question possible duplicate of [Python: How do I pass a string by reference?](http://stackoverflow.com/questions/13608919/python-how-do-i-pass-a-string-by-reference) – McGrady Mar 25 '17 at 10:07
  • 1
    @McGrady, voted to close. – falsetru Mar 25 '17 at 10:08