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)
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
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):
I tried to solve it by inserting the statement
if __name__ == '__main__': in f1 before setting the values of
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?
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)