创建python拼字游戏功能

时间:2017-04-08 03:00:17

标签: python python-2.7

我试图创建一个拼字游戏功能,它接受一串字母并根据字母返回分数。 到目前为止,这是我的代码:

def scrabble_score(rack):
    count = 0
    for letter in rack:
        if letter == "EAIONRTLSU":
            count += 1
            return count
        elif letter == "DG":
            count += 2
            return count
        elif letter == "BCMP":
            count += 3
            return count        
        elif letter == "FHVWY":
            count += 4
            return count
        elif letter == "K":
            count += 5
            return count
        elif letter == "JX":
            count += 8
            return count
        else:
            letter == "QZ"
            count += 10
            return count

然而,当我试图调用该函数时

    scrabble_score("AABBWOL")

当它应该返回14时返回10?

1 个答案:

答案 0 :(得分:0)

代码有两个问题:

  • return语句应该只调用一次, for迭代结束后,所以它可以汇总所有字母值
  • 每个if语句应检查字母是 字符串,而不是等于具有特定值的字母列表。

然后它看起来像:

def scrabble_score(rack):
    count = 0
    for letter in rack:
        print letter
        if letter in "EAIONRTLSU":
            count += 1
        elif letter in "DG":
            count += 2
        elif letter in "BCMP":
            count += 3
        elif letter in "FHVWY":
            count += 4
        elif letter in "K":
            count += 5
        elif letter in "JX":
            count += 8
        else:
            count += 10
    return count

返回:14