作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个函数,使用 Python Dictionary 来计算英语单词的拼字游戏得分。我快到了,但我不断收到恼人的错误:
代码如下:
d = {"0":'blank',
"1":'A, E, I, L, N, O, R, S, T, U',
"2":'D, G',
"3":'B, C, M, P',
"4":'F, H, V, W, Y',
"5":'K',
"8":'J, X',
"10":'Q, Z',}
w = input("enter a word")
def scrab(w): #define function
tot = 0
w.upper()
for key in w:
tot = tot + d[key]
return tot
scrab(w)
print(tot, w)
输出:
Traceback (most recent call last):
File "C:/Users/Bola42/Downloads/IsaiahSLab13Dictionary.py", line 65, in <module>
scrab(w)
File "C:/Users/Bola42/Downloads/IsaiahSLab13Dictionary.py", line 58, in scrab
tot = tot + d[key]
KeyError: ' '
帮忙解决一下吗?这是怎么回事?
最佳答案
你的键和值是倒着的。您使用分数作为字典中的键,使用字母字符串作为值。此外,您没有对输入值使用 strip()
,因此您正在处理附带的空格,而不是单独的字母字符。
关于python - 为什么我会收到此 KeyError 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58602521/
我是一名优秀的程序员,十分优秀!