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

Take the data from a function in another python file

What I am trying to do is take execute a function and be able to take the data of the variables that that function offers me.

Here is an example of my code:

# test.py
def display(var1,var2):
    sum = var1+var2
    print(sum)

# main.py
from test import *
display(1,2)
print(sum)

You can see that from the main.py file I try to call the function to add the numbers 1+2 (that works perfectly) and print the sum result (in this I have problems). How do I get the value of that variable without printing it from test.py?

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 call return to pass a value back to the caller, which you can then assign to a variable (be careful about using sum as a variable name, as that overwrites the built-in function in the location where you do that):

# test.py
def sum_values(var1, var2):
  return var1 + var2

# main.py
from test import *
summed = sum_values(1,2)
print(summed)

I renamed the display function to sum_values since it no longer displays a value, but returns the summed value instead.

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