I am trying to define a basic function in python but I always get the following error when I run a simple test program;
>>> pyth_test(1, 2)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pyth_test(1, 2)
NameError: name 'pyth_test' is not defined
Here is the code I am using for this function;
def pyth_test (x1, x2):
print x1 + x2
UPDATE: I have the script called pyth.py open, and then I am typing in pyth_test(1,2) in the interpreter when it gives the error.
Thanks for the help. (I apologize for the basic question, I’ve never programmed before and am trying to learn Python as a hobby)
import sys
sys.path.append ('/Users/clanc/Documents/Development/')
import test
printline()
## (the function printline in the test.py file
##def printline():
## print "I am working"
Yes, but in what file is
pyth_test‘s definition declared in? Is it also located before it’s called?Edit:
To put it into perspective, create a file called
test.pywith the following contents:Now run the following command:
You should see the output you desire. Now if you are in an interactive session, it should go like this:
I hope this explains how the declaration works.
To give you an idea of how the layout works, we’ll create a few files. Create a new empty folder to keep things clean with the following:
myfunction.py
program.py
Now if you run:
It will print out 3. Now to explain what went wrong, let’s modify our program this way:
Now let’s see what happens:
As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.
Now then, if we run the interactive python session:
The same process applies. Now, package importing isn’t all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!