2014-10-19 51 views
0
inventory = { 
    'gold' : 500, 
    'sack' : ['rock', 'copper wire'], 
    'weapons rack' : ['pistol', 'MP-5', 'grenade'], 
    'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'], 
} 

print "You have " + inventory['gold'][0] + " coins!" 

我得到錯誤信息打印命令不採取行動:在Python編碼,如預期

line 8, in <module> 
    print "You have " + inventory['gold'] + " coins!" 
TypeError: 'int' object has no attribute '__getitem__' 

爲什麼不控制檯打印出來"You have 500 gold coins!"

回答

2

gold不是列表;您正嘗試索引500整數。刪除[0]

print "You have", inventory['gold'], "coins!" 

請注意,我用的逗號,不是+,因爲你不能只是連接字符串和整數這樣。另一種方法是將整數轉換爲字符串第一:

print "You have " + str(inventory['gold']) + " coins!" 

你也可以把黃金價值到列表:

inventory = { 
    'gold' : [500], 
    'sack' : ['rock', 'copper wire'], 
    'weapons rack' : ['pistol', 'MP-5', 'grenade'], 
    'ammo pouch' : ['Pistol ammo', 'MP-5 ammo'], 
} 

注意[...]方括號的500值出現。然後您的[0]再次適用:

print "You have", inventory['gold'][0], "coins!"