无法理解变量的定义位置

2024-06-16 12:01:47 发布

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

好的,我正在学习python课程,我的代码是正确的,但是我还没有完全理解它。我不得不在论坛上找到正确的答案。代码如下:

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 scrabble_score(word):
    total = 0
    #Make my word lowercase even when i type in caps
    t = word.lower()

    for key in t:
        total += score[key]
    return total
print scrabble_score(raw_input("Your word: "))

我什么都有,除了这个:

total += score[key]

脚本如何知道“score”变量是什么?我还没给它下定义。这是全局变量吗? 编辑:问这个问题的时候我有点累(准确地说是醒了23-25个小时)。我现在看到我实际上定义了变量。你知道吗


Tags: key答案代码inmakemydef论坛
1条回答
网友
1楼 · 发布于 2024-06-16 12:01:47

如果需要,您可能需要更改此解决方案:

def scrabble_score(word,score): # score doesn't need to be global
    total = 0
    t = word.lower()
    for key in t:
        total += score[key]
    return total

x = raw_input("Enter word: ")
# declare what score is here
print(srabble_score(x,score))

相关问题 更多 >