gpt4 book ai didi

python - 为什么我会收到此 KeyError 错误?

转载 作者:行者123 更新时间:2023-12-01 07:01:35 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com