Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting a variable in function outside of the function in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading