Why am I Getting a Nameerror When I Try to Call My Function

Why am I getting a NameError when I try to call my function?

You can't call a function unless you've already defined it. Move the def createDirs(): block up to the top of your file, below the imports.

Some languages allow you to use functions before defining them. For example, javascript calls this "hoisting". But Python is not one of those languages.


Note that it's allowable to refer to a function in a line higher than the line that creates the function, as long as chronologically the definition occurs before the usage. For example this would be acceptable:

import os

def doStuff():
if os.path.exists(r'C:\Genisis_AI'):
print("Main File path exists! Continuing with startup")
else:
createDirs()

def createDirs():
os.makedirs(r'C:\Genisis_AI\memories')

doStuff()

Even though createDirs() is called on line 7 and it's defined on line 9, this isn't a problem because def createDirs executes before doStuff() does on line 12.

Why am I getting a NameError when I've defined my variable name in a function?

Look for the 'variable scope' in your documentation or tutorials.

The net_affect variable is local to na function.
You cannot access it from the outside, and it is deleted when the function returns.

You can alternatively :

  • define the variable outside of the function, and indicate that you are using it in the function

    net_affect = None
    def na():
    ...
    global net_affect
    net_affect = div_h_m - div_s_t

  • return the value from the function and catch the returned value

    def na():
    ...
    net_affect = div_h_m - div_s_t
    ...
    return net_affect # return the value

    ...
    net_affect_new = na() # catch the value

    Note: net_affect_new could be called net_affectbut they are not the same variables, they are in two different scopes.

Why is program giving NameError even after defining function?

You need to define the function before you actually call it, unless you're using classes of course.

#function
def register(event):
pass

register_btn = Button(main_screen,text = "Register", bg = "grey",width = "30", height = "2")
register_btn.pack()
register_btn.bind("<Button-1>", register)

function is not defined error in Python

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:

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, we'll 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, let's modify our program this way:

# Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)

# Our function is pulled in here
from myfunction import pyth_test

Now let's 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 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!

Name error: 'self' not defined - when calling a function to create in-class variables

The way you have it, vocabulary, vocabulary_size = self.get_vocabulary() is being executed when the class is being defined, so there is no self. The latter is the name of the first argument passed to methods of a class and is the instance of the class (that was previously created) on which to operate.

The proper way to do this would be to call get_vocabulary() method from the __init__() method when an instance of the class exists and is being initialized.

Here's what I mean:

class Documents:
def __init__(self, input_file):
self.input_file_ = input_file # List in which each element is a list of tokens
self.vocabulary, self.vocabulary_size = self.get_vocabulary()

assert type(self.input_file_) is list, 'Input file is not a list'
assert type(self.input_file_[0]) is list, 'Elements in input file are not lists' # Only checks first instance, not all. But should suffice

def get_vocabulary(self):
vocabulary = set([el for lis in self.input_file_ for el in lis])
return vocabulary, len(vocabulary)

Comment (off-topic):

In languages that have classes and support object-orientated code like Python, it's usually best to avoid type-checking as much as possible because it doesn't support subtyping — but you can overcome that limitation when it is done by using the built-in isinstance() built-in function.

This implies that it would probably be better to do the following in your __init__() method:

    assert isinstance(self.input_file, list), 'Input file is not a list'
assert isinstance(self.input_file_[0], list), 'Elements in input file are not lists' # Only checks first instance, not all. But should suffice

Call a function in python, getting '(function) is not defined'?

Move the function definition to before the lines that use it.

def ballone():
# ...

if workout == "y":
ballone()
elif workout == "n":
print("Okay.")
sys.exit("Not working out if you won")
else:
sys.exit("Could not understand")

Functions are stored in identifiers (variables), just like your workout value. If you don't define it first, how is Python to know it'll be defined later?



Related Topics



Leave a reply



Submit