无法理解变量的定义位置

时间:2014-12-17 21:33:57

标签: python loops for-loop

好吧,我正在关注这个codecademy 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]

脚本如何知道“得分”变量是什么?我没有在任何地方定义它。这是一个全局变量吗? 编辑:在问这个问题时我有点累了(确实已经醒了23-25个小时)。我现在看到我实际定义了变量。

1 个答案:

答案 0 :(得分:0)

如果需要,您可能希望将解决方案更改为:

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))
相关问题