从使用 python 自动化无聊的东西,有一个挑战,它要求您制作一个脚本来显示幻想游戏中的用户清单: 我已经这样做了:
def displayInventory(inventory):
global totalItems
totalItems = 0
print('Inventory:')
for key, value in stuff.items():
print(f'{value} {key}')
totalItems += int(value)
print('Total Items:' + str(totalItems))
之后,它会给你一个名为dragonLoot的列表:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
它要求您制作一个脚本,将来自 DragonLoot 的值添加到库存中。
我的代码如下:
def addToInventory(stuff, addedItems):
for key, value in dragonLoot.Counter():
for key, value in stuff.items():
if key == dragonLoot[key]
then stuff[value] += int(dragonLoot[value])
else stuff[dragonLoot[key]] = dragonLoot[value]
我收到了这个错误。
File "<string>", line 18
if key == dragonLoot[key]
^
SyntaxError: invalid syntax
我不知道这是什么意思。
答案 0 :(得分:1)
好的,所以问题是我使用 if then 语句作为条件而不是 if: 语句。 dfundako 和 Johnny Mopp 指出了这一点。并感谢 Kevin Crum 指出缩进的语法错误。
答案 1 :(得分:0)
python 强制使用 if 语句的缩进和语法
if statement:
execute
注意冒号和缩进