-1

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.

jxaiye
  • 13
  • 4
  • FYI, you're not doing anything with the variables in the function. You subtract `amount` from the value of `From`, but the result of that calculation isn't stored anywhere and thus nothing is happening. – deceze Sep 06 '22 at 11:17
  • Related: [Basic Python OO bank account](https://codereview.stackexchange.com/questions/160840/basic-python-oo-bank-account). – jarmod Sep 06 '22 at 13:12

1 Answers1

1

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
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
  • Thanks for the answer. What if I need the 'From' and 'To' to be inputs? – jxaiye Sep 06 '22 at 11:48
  • 1
    @jxaiye What does that mean? You should not be doing something like this to begin with. A function should accept arguments and return values. It should not be manipulating outside variables, this just leads to spaghetti code. – deceze Sep 06 '22 at 11:49
  • @deceze, okay, I know that I probably made a stupid decision in writing the example code that I used, but what I was meant to do is having the function to be able to subtract any amount from any two predefined variables. – jxaiye Sep 06 '22 at 12:03
  • @jxaiye `def sub(a, b): return a - b`; then on the *calling side* of this function you worry about what variables to pass in and what variable to assign the result to (`foo = sub(From, 100)`). The variable names should *not be hardcoded* inside the function. – deceze Sep 06 '22 at 12:05
  • @deceze I was trying that but I wasn't sure I was doing it correctly. If I add 'From' to 'To' as the parameter as well as global I get an error. – jxaiye Sep 06 '22 at 12:12