How do I solve the NameError: name 'randomResponce' is not defined - python

This the code that has the error:
print("Through 1-10 write a number that is going to represent how far you should throw the ball for " + playerCMD4 + "to catch") ; sleep(float(speed))
playerNumberCMD = raw_input()
import random
def allResponses(arg1):
allResponses = arg1
allResponses = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def randomResponse(arg1):
randomResponse = arg1
randomResponse = random.choice(allResponses)
if randomResponce == playerNumberCMD:
print(playerCMD4 + " caught the ball.") ; sleep(float(speed))
The error I get is this:
Traceback (most recent call last):
File "classref3.py", line 3, in <module>
class Dog:
File "classref3.py", line 50, in Dog
if randomResponce == playerNumberCMD:
NameError: name 'randomResponce' is not defined
Was Defnot the correct way to go or is it something else?

As the error states you have not defined the variable "randomResponce".
If you look at the previous line where you think you have defined the variable, you have defined "randomResponse". Note the different spelling. The spelling needs to be the same.
I would also caution against using the same name for a variable and a function in the same script.

Related

Why does my PyCharm console not run my function?

def is_table(tab):
if len(tab) != 3:
return False
valid = (-1, 0, 1)
for a in range(0, 3):
if len(tab[a]) != 3:
return False
for b in range(0, 3):
if tab[a][b] not in valid:
return False
return True
When I try to run is_table(((0,0,0),(0,0,0),(0,0,0))) on console, I get this error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'is_table' is not defined
Can anyone explain why? My function is clearly defined, but it still doesn't run on console.
The python console dont know about your files functions. First, edit your file name, removing any space, e.g., jogo_do_galo.py (or another name, like jogo_do_mengao).
Open the python console, and try:
>>> from jogo_do_galo import *
>>> tab = ((True, 0, 0), (0, 0, 0), (0, 0, 0))
>>> eh_tabuleiro(tab)
This will work.
Did you define the function inside the console, or in a separate file?
If you defined the function in a separate file, you'll need to run the file before the function will be recognized by the console.
Found an answer. Right-clicked on file name, settings, run on console.

How to write method in class that deletes an entire list including itself?

I have a class with a method called delete that should completely erase the "hold_files" variable. I'd like to mimic deleting an actual folder in the terminal, then itself. For example, "rm -f". Is that possible?
Also, how would I prove that hold_files is completely gone?
class directory:
hold_files = [
'test1.txt', 'test2.py',
{'/desktop': ['computer.txt','tfile.doc',
{'/steph':{
'/pictures': [
'hello.gif',
'smile.gif',
'run.gif'
]},
'/work':[
'file1.txt',
'file2.txt'
]
}]
}
]
#recursively delete folder
def delete(itself):
#if dictionary, call self, else delete
if len(itself)>0:
for f in itself:
print(type(f))
if type(f) is dict:
delete(f)
else:
itself.remove(f)
This is calling the method:
directory.delete(hold_files)
Thank you.
You should be able to use del to delete a variable, and then try using the variable to check if it's really gone. If you get an error, it's gone.
`
>>> number = 1
>>> del number
>>> data = number
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
data = number
NameError: name 'number' is not defined
>>>
`

NameError creating instance of imported class

I have a subclassed Course class as follows:
# course.py
class Course:
"""Represent a single Course"""
kind = 'Gen Ed'
def __init__(self, name, number) :
self._name = name # 'private' instance variable\
self._number = number
self.__display()
def display(self):
print(self.kind,"Course:" , self._name, self._number, sep=" ")
__display = display # private copy
class CSCourse(Course):
"""Represent a single CS Course"""
kind = 'CS' # class variable shared by all CSCourses
def __init__(self, name, number, language, numberOfPrograms):
Course.__init__(self, name, number)
self._language = language
self._numberOfPrograms = numberOfPrograms
def display(self):
Course.display(self)
print('Language', self._language,
'Number Of programs:', self._numberOfPrograms, sep = ' ')
I import the module as follows:
>>>from course import *
This does not throw any exception, but then when I issue the following to call the constructor, I get the error below?
>>> cs360=CSCourse("Special Topics", 360, "python", 21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
What am I doing wrong please? I did also try to see what methods are available in the classes imported. It seems nothing is being imported!
>>> import inspect
>>> inspect.getmembers(Course, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Course' is not defined
>>> inspect.getmembers(CSCourse, lambda a:not(inspect.isroutine(a)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'CSCourse' is not defined
For anyone else having this problem, check if you have circular imports (in file a.py from b import * and in file b.py from a import *). Python doesn't seem to raise an exception when that happens, but the import doesn't work. Restructuring the code to remove the circular import fixed the problem for me.

Can't call function inside function in exec() environment

I have some python (2.7) code using exec() :
import math
def some_function(a, b):
return a+b
safe_dict = { 'Sqrt': math.sqrt, 'Smurf': some_function, "__builtins__": None }
with open('my_file.py') as f:
exec(f.read(), safe_dict, {})
print('The End')
And "my_file.py" is:
print('in exec script')
print('sqrt(2) = %f' % Sqrt(2)) # Call to math.sqrt through name 'Sqrt' given in globals
print('3+4 = %d' % Smurf(3, 4)) # Call to some_function through name 'Smurf' given in globals
def my_func(x):
return Sqrt(2+x)
print("my_func: %f" % my_func(1)) # No problems
def my_func2(x, f):
return f(x-1)
print("my_func2: %f" % my_func2(5, my_func)) # No problems too
def my_func3(x):
return my_func(x-1) # Here, leads to a "NameError: global name 'my_func' is not defined" in the next line
print("my_func3: %f" % my_func3(5))
I don't understand why there is a NameError in my_func3 when it tries to call my_func.
Why my_func3 is not able to call my_func, even if previously defined ?
Is there a way to make it work (not with my_func defined in the main module) ?
edit
Error is:
Traceback (most recent call last):
File "main.py", line 9, in <module>
exec(f.read(), safe_dict, {})
File "<string>", line 16, in <module>
File "<string>", line 15, in my_func3
NameError: global name 'my_func' is not defined

Python NameError when var IS most definitely defined

def make_pdf(self):
self.get_filez()
self.get_client()
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
style = libxslt.parseStylesheetDoc(self.xsl_file)
transformation = style.applyStylesheet(self.xml_file,None)
style.saveResultToFilename("tmp/"+file_name+".fo",transformation,0)
style.freeStylesheet()
self.xml_file.freeDoc()
transformation.freeDoc()
fop_cmd = "/usr/bin/xmlgraphics-fop"
#file_name = self.tpa+"_"+self.be+"_"+self.batch_num
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
#fop_transform = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
#fop_log = "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n"
#fop_log = fop_log + time.strftime('%Y-%m-%d %R:%S')+"\n"
#fop_log = fop_log + file_name+".fo" + "\n"
#fop_log = fop_transform.communicate()[0]+"\n"
#f = open("/tmp/error_log","a")
#f.write(fop_log)
#f.close()
OK If I comment out the cmd variable declaration the code runs and makes an fo file correctly. With is uncommented like it is above, I get a NameError on file_name is not defined (which it is in the top). If I uncomment the second declaration of file_name right above the cmd declaratioin, it thows a NameError on self. '.' In the past when this sort of thing happens, it is a syntax error. I am missing it, please helpz!
When the second declaration of file_name is commented out:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 39, in MakePdfs
cmd = [fop_cmd,"-fo","tmp/"+file_name+".fo","-pdf","tmp/"+file_name+".pdf"]
NameError: name 'file_name' is not defined
When the second declaration of file_name is uncommented:
Traceback (most recent call last):
File "make_pdfs.py", line 11, in ?
from MakePdfs import MakePdfs
File "/home/khouser/removed/removed/MakePdfs.py", line 16, in ?
class MakePdfs:
File "/home/khouser/removed/removed/MakePdfs.py", line 38, in MakePdfs
file_name = self.tpa+"_"+self.be+"_"+self.batch_num
NameError: name 'self' is not defined
Mysterious NameErrors may arise from your file containing invisible control characters. On unix machines, you can spot these errors by looking at the output of
cat -A filename.py
Try to print file_name after each line, to see if somebody is removing the "file_name" variable from your namespace.
In addition, to be more pythonic (and efficient), use
file_name = "_".join((self.client_id, self.client_name, self.batch_num))
to concatenate strings.
If you're assigning file_name here:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
And you're getting a NameError reporting, that file_name is not defined, then try wrapping the operation in a try..except, to see what is going wrong:
try:
file_name = self.client_id+"_"+self.client_name+"_"+self.batch_num
except NameError as err:
print err, 'failed, here is some debug stuff:'
print "CLIENT ID =", self.client_id
print "CLIENT NAME =", self.client_name
print "BATCH NUM =", self.batch_num
If any of this is failing, this will set you on the course to finding out why and narrowing down the cause of it.

Categories

Resources