[英]I got an error in python 3 about Keyerror
I got this code from udemy course:我从 udemy 课程中得到了这段代码:
def choose_magic(self):
i = 1
print(bcolors.OKBLUE + bcolors.BOLD + "Magic" + bcolors.ENDC)
for spell in self.magic:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
i += 1
When I try to call this function I got this error:当我尝试调用此 function 时,出现此错误:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
KeyError: 'cost'
I got this from udemy course and when I try to run return that error.我从 udemy course 得到这个,当我尝试运行时返回该错误。
The spell
dict doesn't have a "cost"
key. spell
字典没有"cost"
键。 You'll need to look at where it's initialized (ie the members of self.magic
).您需要查看它的初始化位置(即self.magic
的成员)。
FWIW, this print
statement: FWIW,此print
声明:
print(str(i) + ":", spell["name"], "(cost:", str(spell["cost"]) + ")")
works a lot better in Python 3 as an f-string:在 Python 3 作为 f 字符串时效果更好:
print(f"{i}: {spell['name']} (cost: {spell['cost']})")
but you still need to sort out that cost
thing before it'll work.但是你仍然需要在它起作用之前解决这个cost
问题。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.