Home > Blockchain >  How to use the data from a function in another script?
How to use the data from a function in another script?

Time:06-13

What I am trying to do is 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?

CodePudding user response:

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.

  • Related