function is not defined error in Python

function is not defined error in Python

Yes, but in what file is pyth_tests definition declared in? Is it also located before its called?

Edit:

To put it into perspective, create a file called test.py with the following contents:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1,2)

Now run the following command:

python test.py

You should see the output you desire. Now if you are in an interactive session, it should go like this:

>>> def pyth_test (x1, x2):
...     print x1 + x2
... 
>>> pyth_test(1,2)
3
>>> 

I hope this explains how the declaration works.


To give you an idea of how the layout works, well create a few files. Create a new empty folder to keep things clean with the following:

myfunction.py

def pyth_test (x1, x2):
    print x1 + x2 

program.py

#!/usr/bin/python

# Our function is pulled in here
from myfunction import pyth_test

pyth_test(1,2)

Now if you run:

python program.py

It will print out 3. Now to explain what went wrong, lets modify our program this way:

# Python: Huh? wheres pyth_test?
# You say its down there, but I havent gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now lets see what happens:

$ python program.py 
Traceback (most recent call last):
  File program.py, line 3, in <module>
    pyth_test(1,2)
NameError: name pyth_test is not defined

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:

>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3

The same process applies. Now, package importing isnt all that simple, so I recommend you look into how modules work with Python. I hope this helps and good luck with your learnings!

It works for me:

>>> def pyth_test (x1, x2):
...     print x1 + x2
...
>>> pyth_test(1,2)
3

Make sure you define the function before you call it.

function is not defined error in Python

In python functions arent accessible magically from everywhere (like they are in say, php). They have to be declared first. So this will work:

def pyth_test (x1, x2):
    print x1 + x2

pyth_test(1, 2)

But this wont:

pyth_test(1, 2)

def pyth_test (x1, x2):
    print x1 + x2

Leave a Reply

Your email address will not be published. Required fields are marked *