Why is python shell throwing a NameError where as windows console a ValueError?
def PrintArgs(*arg):
list = ['1','2']
for i in arg:
try:
print(list[int(i)])
except ValueError:
print('Please enter integer value')
except NameError:
print('Name Error')
if __name__ == '__main__':
PrintArgs(*sys.argv[1:])
Providing the following arguments to Windows Console gives this output:
Here is how I call the code in windows console:
C:\>C:\Python34\python C:\Users\User\Documents\PYTest\Test.py 0 a
1
Please enter integer value
Providing the following arguments to Python Shell does not display the cusom error for NameError as mentioned in the code above, but mentions the following error:
PrintArgs(0,a)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
PrintArgs(0,a)
NameError: name 'a' is not defined
In the code example you've provided you define a list i, then you iterate over a collection called list you never initiated, and assign the values in this list to i, thus dropping the original value. I guess you only provided a part of your code, please provide a minimum working example.
If I try to reproduce your problem, I only get a type error, for iterating over a list which is not initialized.
Related
I have two models:
class Someinfo(models.Model):
name = models.CharField(max_length=200)
#something else
class OtherInfo(models.Model):
name2 = models.CharField(max_lenth=200)
related_someinfo = models.ManyToManyField(Someinfo)
#something else
Now I have created CBV views to create and view them. The CreateView works fine and saves info that can be reviewed in admin, but I cannot get the template to display the data on any other view be it FormView, DetailView or any other, because I get this error:
__call__() missing 1 required keyword-only argument: 'manager'
Request Method: GET
Request URL: http://something
Django Version: 2.0.3
Exception Type: TypeError
Exception Value:
__call__() missing 1 required keyword-only argument: 'manager'
Exception Location: /usr/local/lib/python3.5/dist-packages/django/forms/forms.py in get_initial_for_field, line 494
Python Executable: /usr/bin/python3
Python Version: 3.5.3
Checking the line in forms.py it shows that the function that is not working is:
def get_initial_for_field(self, field, field_name):
"""
Return initial data for field on form. Use initial data from the form
or the field, in that order. Evaluate callable values.
"""
value = self.initial.get(field_name, field.initial)
if callable(value):
value = value() # line 494
return value
Any suggestions? I can query the linked objects via shell and they are saved in the database, so I have no idea how to proceed.
Here is my case, I am using django shell:
python manage.py shell
There are two models: Topic and Entry. I tried to get all entries from Topic which id is 1.
>>> Topic.objects.get(id=1)
<Topic: Chess>
>>> t = Topic.objects.get(id=1)
>>> t.entry_set().all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __call__() missing 1 required keyword-only argument: 'manager'
>>> t.entry_set.all()
<QuerySet [<Entry: Ah okey, so when testing for a console.log (or oth...>]>
>>>
The correct command is: t.entry_set.all(), not t.entry_set().all()
use entry_set instead of entry_set()(wihout brackets )
Writing an analytics script for facebook chats with python. The library I'm using (fbchat) sometimes returns None type objects in place of messages. I thought I could catch this with a simple
if message is None:
continue
in my loop through my message list. However, I'm still getting exceptions due to the object being None type. What am I doing wrong here?
Code snippet:
for message in messages:
#sometimes the fbchat library doesn't return a message
if message is None:
continue
#strip the line endings to not mess up the csv
message.text.replace('\n', ' ')
Exact exception:
Traceback (most recent call last):
File "collect.py", line 58, in <module>
message.text.replace('\n', ' ')
AttributeError: 'NoneType' object has no attribute 'replace'
Checking for message.text is None resolves the issue and is what I should have done in the first place.
I've been having some issues with my code, you see I am a beginner at python programming and so I don't understand all the errors, So I would be quite happy for assistance down below is the code, which I have checked intensively just to find the error:
class Animal(object):
def __init__(self,legs,name):
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
self.legs = legs
self.name = name
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)
This is the Error:
Traceback (most recent call last):
File "class.py", line 9, in <module>
roscoe.sleep(4)
AttributeError: 'Animal' object has no attribute 'sleep'
You have a syntax error in the last line.
It should be:
roscoe.sleep(4)
instead of
roscue.sleep(4)
Giving more context since I see you're a begginner at Python. The traceback of Python interpreter (the "program" that runs Python code) tells you what happened. In this case, it says "name 'roscue' is not defined". This is usually a syntax error. Sometimes it can mean that you haven't defined that function. But in this case, it's the former.
Also, going a little bit further, you're probably going to get an error of indentation. In Python, you have to indent every block that you want to put together, either with tabs or with spaces.
Finally, think about your functions, you have to put them in order. Init is a function, and sleep is another function, so after each one you have a block. Different blocks should be indented separately. Here's how the code should look, but revise it instead of running it blindly.
class Animal(object):
def __init__(self,legs,name):
self.legs = legs
self.name = name
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)
Not very new to programming or to python but incredibly green to using pyunit. Need to use it for my new job and I keep getting this error but only sometimes when it is run. My code below.
import unittest
from nose_parameterized import parameterized
from CheckFromFile import listFileCheck, RepresentsFloat
testParams = listFileCheck()
class TestSequence(unittest.TestCase):
#parameterized.expand(testParams)
def test_sequence(self, name, a, b):
if RepresentsFloat(a):
self.assertAlmostEqual(a,b,2)
else:
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
What is happening here is that my test case is pulling a method listFileCheck from another class. What it does is it reads values from the serial port communicating with the control board and compares them with a calibration file. It puts the control board values in an MD array along with the calibration file values. These values can be either str, int, or float.
I used the test case to compare the values to one another however I keep getting this error but only sometimes. After every 3rd or so run it fails with this error.
Error
Traceback (most recent call last):
File "C:\Python34\lib\unittest\case.py", line 57, in testPartExecutor
yield
File "C:\Python34\lib\unittest\case.py", line 574, in run
testMethod()
TypeError: 'NoneType' object is not callable
Process finished with exit code 0
Anyone know why I might be getting this error on occasion?
G'day fellows. I face a problem regarding a global variable which python claims is not defiend even though it is. In essence, I just want to check if an integer contains a decimal place, or the input contains nothing integer related whatsoever. Here is my code:
def Strength1():
try:
global strength1
strength1 = int(input("%s, please enter your desired strength - between 1 and 20\n>"%name1))
strength1int = int(strength1)
def invLoop():
clearScreen()
Invalid()
Strength1()
if int(strength1) <= 0:
invLoop()
if int(strength1) >= 21:
invLoop()
except Exception as exception:
clearScreen()
print("'%s isn't an integer."%strength1)
Strength1()
def Skill1():
try:
global skill1
skill1 = int(input("%s, please enter your desired skill - between 1 and 20\n>"%name1))
skill1int = int(skill1)
def invLoop():
clearScreen()
Invalid()
Skill1()
if int(skill1) <= 0:
invLoop()
if int(skill1) >= 21:
invLoop()
except Exception as exception:
clearScreen()
print("'%s isn't an integer."%skill1)
Skill1()
def Strength2():
try:
global strength2
strength2 = int(input("%s, please enter your desired strength - between 1 and 20\n>"%name2))
def invLoop():
clearScreen()
Invalid()
Strength2()
if int(strength2) <= 0:
invLoop()
if int(strength2) >= 21:
invLoop()
except Exception as exception:
clearScreen()
print("'%s' isn't an integer."%strength2)
Strength2()
def Skill2():
try:
global skill2
skill2 = int(input("%s, please enter your desired skill - between 1 and 20\n>"%name2))
def invLoop():
clearScreen()
Invalid()
Skill2()
if int(skill2) <= 0:
invLoop()
if int(skill2) >= 21:
invLoop()
except Exception as exception:
clearScreen()
print("'%s' isn't an integer."%skill2)
Skill2()
and this is my error:
Traceback (most recent call last):
File "H:\Toby Reichelt\A453\Two Encounters - Developing Dice.py", line 29, in Skill1
skill1 = int(input("%s, please enter your desired skill - between 1 and 20\n>"%name1))
ValueError: invalid literal for int() with base 10: '0.5'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "H:\Toby Reichelt\A453\Two Encounters - Developing Dice.py", line 197, in <module>
mainloop()
File "H:\Toby Reichelt\A453\Two Encounters - Developing Dice.py", line 188, in mainloop
Skill1()
File "H:\Toby Reichelt\A453\Two Encounters - Developing Dice.py", line 41, in Skill1
print("'%s isn't an integer."%skill1)
NameError: global name 'skill1' is not defined
skill1 is not defined because if int(input()) fails and raises an exception, then nothing at all will be assigned to skill1.
First assign the string to a variable, and try to convert afterwards.
try:
global skill1
skill1 = input("%s, please enter your desired skill - between 1 and 20\n>"%name1)
#if the below line crashes, `skill1` will still have the old string value
skill1 = int(skill1)
If your int(input('...')) call fails, an Exception is raised before anything is assigned to skill1. Then you try to print the value of skill1 in your error handling, except that that name hasn't been defined yet.
Either remove skill1 (and strength1, and skill2, and strength2) from the exception handling, or else assign them some default value (None is customary, or sometimes -1) outside of the try block to be certain that they're defined, even if the user inputs a bad value.
This has nothing to do with global variables; in fact it's not clear that declaring skill1 and strength1 as global is being done for any reason at all in your code. Just to be clear, you should check the docs on the global keyword: it does not define a name; all it does is indicate to the parser that any assignments to that name in the local scope should be applied to that name in the module-level scope.
You seem to be expecting that if the user's input isn't a valid integer, skill1 will be defined to... something. Perhaps the raw text of the user's input? In any case, that's not what happens.
If int(input(...)) throws an exception, control goes to the except block without assigning skill1. If you want to have something to print even when the input is invalid, you need to save the result of input separately from converting it to an integer.
global keyword doesn't mean "define variable in global scope", but "when searching for variable to modify, look into global scope, not local scope".
Your code won't run anyway, you have no call to defined functions.
Define variables skill1, skill2, strength1, strength2 in module, not in function, it will solve the problem you've encountered.
PS. global variables are ugly. Don't do this.
The Global Variable Wont Work
it Wont Work Cuz if U'r "try : except :" Fails There Wont Be any Skill1
Why Dont u Define u'r Variables Outside of The Function ? Unless u Got Other ones with The Same Name .
And I dont Recommend Using a Global Variable