Home > Enterprise >  Calling a function that imports its result from another function in Python
Calling a function that imports its result from another function in Python

Time:11-20

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:

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?

CodePudding user response:

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)

CodePudding user response:

One solution would be to simply delete the print functions from f1.
If you still want to be able to print those values but only when you want, simply create functions in f1 like this:

def printFirstFunction(a, b):
    print(fS(a,b))

def printSecondFunction(a, b, y):
    print(fM(a,b,y))

and call these functions only when you need to print those values.

To solve the problem where you wrote the main function, you should provide that code too. Most likely you forgot to intialize those variables or you defined the function before declaring them, but we can't tell if you don't show us that code.

  • Related