This is the simplest of exercises. I just don't understand why it wont work.
Here's my code:
hobbies = []
for i in range(3):
hobby = raw_input("Name a hobby")
hobbies = hobbies.append(hobby)
Basically I want to ask my user 3 times to name one of his hobbies, and store them in a list. But for some reason I'm getting this error,
Traceback (most recent call last):
File "C:/Python27/hobbies.py", line 4, in <module>
hobbies = hobbies.append(hobby)
AttributeError: 'NoneType' object has no attribute 'append'
which I don't really understand.
The problem is that append() will change the list in-place. And when you call this function no value is returned.
The first time you get a None value for the variable hobbies. The second time you try to call the append() method for a None value...
You should not use hobbies = hobbies.append(). Instead use hobbies.append() only.
Related
I have a scenario , where I am trying to get index position of value
My code :
a_set = {22,56,26}
print(a_set[56])
Getting below error
Traceback (most recent call last):
File "<string>", line 5, in <module>
TypeError: 'set' object is not subscriptable
Expected output :
1 -> This the position of 56 from set
The error is explaining a lot here: sets in Python are not subscriptable.
They dont have order relation.
According to your code example, you are trying to ask weather a value exists in the set, right?
In Python you can do it with in operator:
>> print(36 in a_set)
True
or
if (36 in a_set):
my_function()
Sets are by definition completely unordered and unindexed, you cannot get the information with an index directly as that is not what they were made for. As a workaround, you can simply convert the set to a list that is both indexed and ordered.
a_set = {22,56,26}
print(list(a_set)[3]) # converts the set into and displays it's third entry.
To solve your problem, you can use .index() on the new list such as this:
a_set = {1,2,3}
print(list(a_set).index(1))
What's wrong with that code? When I run it tells me this:
Traceback (most recent call last):
line 24, in <module>
people.append(Dict)
AttributeError: 'str' object has no attribute 'append'
My code:
live = 1
while live == 1:
#reading Database
dataRead = open ("db.txt","r")
if dataRead.read() != " ":
dataRead.close()
people = open ('db.txt','r').read()
do = input ('What Do You Want ? (Search , add) :\n')
#add people
if do == 'add':
#Get The New Data
n_Name = input ('enter the new name:\n')
n_age = input ('enter the new age:\n')
#new Dict
Dict = {'Name:':n_Name,'age':n_age}
people.append(Dict)
#adding people to file
dataWrite = open ("db.txt","w")
dataWrite.write(str(people))
dataWrite.close()
live = 0
The problem is, on line 24, you try to append a dictionary to a string. When you read the db file, it read it as a string. Also the code is really messy and there are a lot better ways to do it. But that's besides the point, the append() method is for lists and the variable "people" is a string, according to your error output.
It says that people is str then it doesn't have an append method. You should just concatenate strings to get them together.
Do:
people += '<append string>'
Have in mind you are trying to append a dictionary to a string. This will throw TypeError cause those type of elements can't be concatenated that way. You should do first: str(dict) to concatenate them.
You're also using a reserved word like dict as a variable. Change it to my_dict or other allowed name.
I am trying to write a targeting priority script for an AI. My goal is to rank targets based on their score of damage_per_shot / rate_of_fire and reorder the list based on highest targeting priority. I finally hit an error I didn't know how to work around however. 'NoneType' object has no attribute 'get'
I am very new to Python and built this mostly by Googling the terms I would have used in Ruby. I would also appreciate suggestions about how to do this in the correct Python "style" if I made any major errors.
enemyList=[{"id":1,"damage_per_shot":10,"rate_of_fire":2},{"id":3,"damage_per_shot":0,"rate_of_fire":0},{"id":2,"damage_per_shot":14,"rate_of_fire":2}]
#enemyList=unit_client.ask_nearest_enemy()
print(enemyList)
aDict = {}
for item in enemyList:
if(item["rate_of_fire"]!=0):
currScore=float(item["damage_per_shot"]/item["rate_of_fire"])
aDict[item['id']] = currScore
def focus_fire2(data=None, *args, **kawargs):
print("===ff2===")
target_id=sorted(aDict, key=data.get)
print(target_id)
print("attacking: "+str(id))
#unit_client.do_attack(key)
##remove item from list
if(len(aDict)>0):
del aDict[target_id] #remove the object from the dict after done
print(aDict)
focus_fire2()
else:
return 0
#unit_client.when_item_destroyed(target, aDict.pop(key,None))
#unit_client.when_item_destroyed(target, focus_fire2)
focus_fire2()
The traceback looks like
[{'damage_per_shot': 10, 'id': 1, 'rate_of_fire': 2}, {'damage_per_shot': 0, 'id
': 3, 'rate_of_fire': 0}, {'damage_per_shot': 14, 'id': 2, 'rate_of_fire': 2}]
===ff2===
Traceback (most recent call last):
File "ffire.py", line 26, in <module>
focus_fire2()
File "ffire.py", line 13, in focus_fire2
target_id=sorted(aDict, key=data.get)
AttributeError: 'NoneType' object has no attribute 'get'
Just replace
sorted(aDict, key=data.get)
by
sorted(aDict, key=aDict.get)
In your function focus_fire2, you set data to None by default in the arguments of the function definition. Unless you set it to something other than None when you call it, like focus_fire2(data=something), then it's equal to None when you do, data.get() later on. And there lies your error I think. You are treating a NoneType like a dict. If you're calling get on it, you probably should be setting it equal to some dict or other.
You get an error, because run function without arguments, and by default data have a None type. And for me it's not good idea, set default value as None for non optional arguments. You need run function with argument focus_fire2(aDict), or change target_id=sorted(aDict, key=data.get) to target_id=sorted(aDict, key=aDict.get, reverse=True) you get in target_id, list of sorted key from aDict, where first value is higher. But target_id is a list and this code is wrong del aDict[target_id]. What must be in target_id?
I'm pretty sure that my error is a very small and stupid thing but I'm not capable to see it!! :(
I have a defined dictionary: self.names_to_nodes, and I want to access to one of its members with the key that I have.
Here is a piece of my code:
print "Result " + str(len( self.names_to_nodes))
if i in self.names_to_nodes:
print "ESTA"
member = self.names_to_nodes.get(i)
ancestrosA.append(member.get_parent())
And I get this exit and this error:
Result 17
ESTA
143 print "ESTA"
144 member = self.names_to_nodes.get(i)
145 ancestrosA.append(member.get_parent())
146 i = member.get_parent()
147 ancestrosA.append(self.founder)
AttributeError: 'NoneType' object has no attribute 'get_parent'
How is this possible???
Thanks for your help! How get(i) is not finding the element if the key is in the dictionary?
BR,
Almu
You need to move the lookup inside the if statement if you want to make sure it exists before checking:
if i in self.names_to_nodes:
print "ESTA"
# only does a lookup if the key exists
member = self.names_to_nodes[i]
ancestrosA.append(member.get_parent())
You check if it exists but still check i outside the if so whether i exists or not you always do a lookup.
dict.get returns a value whether the key is in the dictionary or not. Example:
>>> x = {1:2}
>>> print(x.get(100))
None
Try using regular item access instead. Then your code will raise an exception if you try to get a nonexistent value. Example:
>>> x = {1:2}
>>> print(x[100])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100
(Readers may ask, "but how could i not be a key in the dictionary? 'ESTA' was printed, and that only occurs when the membership test successfully passes". I'm assuming that this code is inside a for loop that changes the value of i, and the printed 'ESTA' is from the previous iteration, which ran without problems.)
I want to split the History_Data with , and put into an dictionary , then put the dictionary to a one dimension array then access them . But it seems have some error . How can I solve that?
here is my code
History_Data = ("2004/01/20,000006,29,28,13,33,34,32,43",
"2004/01/18,000005,36,22,44,34,46,29,37",
"2004/01/16,000004,02,13,34,44,06,40,14",
"2004/01/14,000003,29,28,13,33,34,32,43",
"2004/01/12,000002,32,15,14,29,39,20,43",
"2004/01/10,000001,30,29,18,34,19,28,12")
Dataset = ()
for Line in History_Data:
Item = {}
Parts = Line.split(",")
Item['date'] = Parts[0]
Item['serial'] = Parts[1]
Item['numbers'] = Parts[2:len(Parts)]
Dataset.append(Item)
for Element in Dataset:
print(Element)
Error message
Traceback (most recent call last):
File ".\1.py", line 18, in <module>
Dataset.append(Item)
AttributeError: 'tuple' object has no attribute 'append'
tuple is an immutable type in Python so gets no method append. For your need, use a list, Dataset = [], not a tuple, Dataset = ().