Setting a variable in function outside of the function in python

Viewed 37

I'm fairly new to python and I'm wondering how to store a variable that has been changed in a function to the rest of the script. Using a simple example of transfering a number between two defined variables:

From = 1000
To = 0

def transfer(From, To, amount):
    From - amount
    To + amount

transfer(From, To, 100)
print(From)

Even though 'From' has been subtracted by 100 in the function, if I try to access it outside the function it is still the original value. I wish to make the changes in the function global, but not sure how to do that.

Sorry if this is a trivial question, but if someone can explain the reasons and workings behind this it would be great. Thank you.

1 Answers

You can modify a global variable from within a function by using the global keyword

From = 1000
To = 0

def transfer(amount):
    global From, To
    From -= amount
    To += amount

transfer(100)
print(From)

900
Related