Skip to content
Advertisement

function is not defined error in Python

I am trying to define a basic function in python but I always get the following error when I run a simple test program;

JavaScript

Here is the code I am using for this function;

JavaScript

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)


JavaScript

Advertisement

Answer

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.py with the following contents:

JavaScript

Now run the following command:

JavaScript

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

JavaScript

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

JavaScript

program.py

JavaScript

Now if you run:

JavaScript

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

JavaScript

Now let’s see what happens:

JavaScript

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:

JavaScript

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!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement