python中的scrakable游戏

2024-03-28 16:58:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我对字典非常陌生,我正在尝试用python实现一个简单的scratable游戏,它返回我输入的每个单词的分数。 但是我不太熟悉字典,我想知道我的代码有什么问题

我编了一本字典,每个字母都有自己的分数

points = {'A':1, 'B':3, 'C':3, 'D':2, 'E':1, 'F':4, 'G':2,
'H':4, 'I':1, 'J':8, 'K':5, 'L':1, 'M':3, 'N':1,
'O':1, 'P':3, 'Q':10, 'R':1, 'S':1, 'T':1, 'U':1,
'V':4, 'W':4, 'X':8, 'Y':4, 'Z':10}

def scraable():
    total_score=0
    word=input('Digit a word\n')
    for i in word:
        total_score=total_score+points[i]
    return total_score
print(scraable())

它给了我一个关键错误'p',我不知道这是什么类型的错误


Tags: 代码游戏字典def错误字母单词分数
2条回答

最具python风格的方法是使用理解和sum

points = {'A':1, 'B':3, 'C':3, 'D':2, 'E':1, 'F':4, 'G':2,
'H':4, 'I':1, 'J':8, 'K':5, 'L':1, 'M':3, 'N':1,
'O':1, 'P':3, 'Q':10, 'R':1, 'S':1, 'T':1, 'U':1,
'V':4, 'W':4, 'X':8, 'Y':4, 'Z':10}

def scraable():
    word=input('Digit a word\n')
    return sum(points.get(l.upper(), 0) for l in  word)

print(scraable())

我们使用dict.get来避免字典中没有的东西得到0点的默认值时出错。 此外,我们使用str.upper,因为在dict中,所有键都是大写的,所以如果输入是小写的,它将失败("W" != "w"

如评论中所说,请用大写字母填写如下:

for i in word:
  total_score=total_score+points[i.upper()]

相关问题 更多 >