请问这段程序哪里错误了?求指教,错误显示
#displayInventory(inv)
NameError: name 'inv' is not defined
suff={'rope':1,'torch':6,'gold coin':42,'dagger':1,'arrow':12}
def displayInventory(inventory):
print('Inventory')
for x,y in inventory.items():
print(str(y)+' '+x)
itemTotal=0
itemTotal += y
print('The number of total '+str(itemTotal))
displayInventory(suff)
def addToInventory(inventory,addedItems):
#you coda gose here
inv={'gold coin':42,'rope':1}
dragonLoot=['gold coin','dagger','gold coin','gold coin','ruby']
inv=addToInventory(inv,dragonLoot)
displayInventory(inv)
发现了吗?你没有调用函数addToInventory。所以inv在这个程序中不存在。即使你调用了,这个程序也是错的。如果调用,程序将在调用这个函数的时候定义一个inv,然后在函数结束的时候将其销毁(看的出你是新手,如果不知道什么叫销毁,你可以把它理解成删除),这就是所谓“局部变量”。一个解决办法是:在程序最前面加上:
inv: dict
这样会声明一个字典,叫inv,然后在addToInventory函数里面第一行写上:
global inv
这是告诉解释器,我要在addToInventory这个函数里面使用inv这个全局变量。
最后,在displayInventory(inv)的前面,加上这行语句:
addToInventory(我不知道你的程序是干吗用的,在这里填上参数)
第24行的inv没有定义,你只定义了一个局部变量inv
第24行的inv没有定义,你只定义了一个局部变量inv