0

I want to change a variable in function through its helper function. I tried the following:

def f():
    e = 70
    print(e) # prints 70
    def helper(e):
        print(e) # prints 70
        e = 100
        print(e) # prints 100
    helper(e) #function called to change e
    print(e)  # Still prints 70 :( Why?

f() #prints 70, 70, 100, 70

Why does it not change the value of e (I passed it as parameter and python doesn't copy values too, so value of e in f should be changed)? Also how can I get the required result?

Saurav Yadav
  • 115
  • 9
  • This is because of scoping: e outside of `helper` is a different variable than e inside. In your case helper just uses e to print sth which is based on e, but afterwards the program continues happily with the only e it has. If you want to receive the result of helper, you should add a return Statement to helper, so that it gives back its result and then write `e = helper(e)` – SpghttCd May 24 '18 at 05:54

1 Answers1

0

e in function f is local to f and you passed argument e. But inside helper when you did e=100 it is another local variable within the scope of helper. So, you should return the value from helper and update e.

you should do this,

def f():
    e = 70
    print(e) 
    def helper(d):
        print(d) 
        e = 100
        print(e)
        return e # prints 100
    e = helper(e) 
    print(e)  

f()
Prakash Palnati
  • 3,231
  • 22
  • 35