I have written the two functions below in the same python file. If I print the answer function it returns the answer of 7 which is expected.
The second function is calling the first function to get the answer.
If I create two python files as below and run it there is an error NameError: name 'math' is not defined.
Why am I not able to create the function that is required to run answer() in the second python file?
I have tried referencing math = 0 to give it a starting variable. My goal is to be able to build functions that I can import into the main python file where that function uses functions created in the main file. The two files are p1.py and p2.py
def math(x,y):
answer = x + y
return answer
def answer():
answer = math(5,2)
return answer
print(answer())
# Returns the answer of 7
def answer():
answer = math(5,2)
return answer
import p1
def math(x,y):
answer = x + y
return answer
print(answer())
# Returns NameError: name 'math' is not defined.
There are a few ways to make it work, you can make answer
take a function as an argument:
def answer(math):
answer = math(5,2)
return answer
and call it with answer(math)
, or you could import it in p1.py by adding from p2 import math
.