I'm using this Scrabble code to translate letters into numbers, but whenever I try to run it, it returns a Key Error: ' ', and I don't know why this happens or how to fix it.
score = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
def tracker():
word = input("Please enter a word.")
total = 0
for i in word:
total = total + score[i.lower( )]
print(total)
return total
def main():
tracker()
main()
Returns the error:
Please enter a word. Yellow
Traceback (most recent call last):
File "H:\Scrabble.py", line 15, in <module>
main()
File "H:\Scrabble.py", line 14, in main
tracker()
File "H:\Scrabble.py", line 10, in tracker
total = total + score[i.lower( )]
KeyError: ' '
Your input probably has a space that is not in the score dictionary. try:
above score
unknown_char=0
#Whatever the unknown char data should be
in tracker()
for i in word:
try:
total += score[i.lower()]
except:
total += unknown_char
In any program that requires user's input, you need to manage input errors .
I suggest using .strip()
method on the word you will iterate on. It'll get rid of the spaces. Also, you might want to check if the character is in your dictionnary, I believe you should do as such :
if i not in word : raise ValueError("Your error message.")
Also, when iterating through your dict, you should use .items()
(python 3.x) or .iteritems()
(python 2.7) if you need the key and the value, as such :
for key, value in your_dict.iteritems():
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.