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

Calling a function that imports its result from another function in Python

I have a code in Python f1 that creates two functions, the second function gets the result from the first one:

a = 3
b = 4

def fS(a,b):
    x = a+b
    return x

y = fS(a,b)
print(y)
    
def fM(a,b,y):
    z = a*b*y
    return z

w = fM(a,b,y)
print(w)

And another code f2 that uses these functions, both imported from the first code:

from f1 import *

a = 6
b = 4
    
c = a+1
d = b+1

p = fS(c,d)
print(p)

q = fM(c,d,p)
print(q)

Function fS gives the sum of two numbers. Function fM gives the product multiplied by the previous result of the sum. In f2, both numbers should be added by 1 before the first function. Running f1, it gives the correct result for y and w:

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

7
84

But running f2, it gives the result from f1 and results from f2:

7
84
12
420

The results are correct but my intention is to print only the results from f2 (p = 12 and q = 420) when running it and not those first two results (7 and 84):

12
420

I tried to solve it by inserting the statement if __name__ == '__main__': in f1 before setting the values of a and b, but got an error message: name 'a' is not defined in y = fS(a,b) because these values cannot be read by running f2. What am I missing here? Is there a way I could do it without creating a new file?

>Solution :

Try wrapping whole code outside defs in f1 in that if. After changing f1 to this code, it should work.



def fS(a,b):
    x=a+b
    return x

def fM(a, b ,y):
    z=a*b*y
    return z


if __name__ == '__main__':
    a = 3
    b = 4
    y = fS(a,b)
    print(y)



    w = fM(a, b, y)
    print (w)
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