为什么我得到“全球名称......未定义”?

时间:2015-04-10 11:45:34

标签: python

我有两段代码,一段用于获得单词分数,另一段用于测试。但是我得到了

NameError: global name 'wordList' is not defined 

这是第一个文件ps4a.py。

# ps4a.py
import random
import string
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'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
}
WORDLIST_FILENAME = "C:/Users/erroric/mit/ProblemSet4/words.txt"
def loadWords():
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r', 0)
    # wordList: list of strings
    wordList = []
    for line in inFile:
        wordList.append(line.strip().lower())
    print "  ", len(wordList), "words loaded."
    return wordList
def getWordScore(word, n):
    score = 0
    bonus = 50
    if word in wordList:
        for i in word:
            score += SCRABBLE_LETTER_VALUES.get(i)
        score *= len(word)
    else :
        print "That is not a valid word. Please choose another word"

if len(word) == n:
    score += bonus
return score

if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)

测试文件

from ps4a import *

#
# Test code
# You don't need to understand how this test code works (but feel free to look it over!)

# To run these tests, simply run this file (open up in IDLE, then run the file as normal)

def test_getWordScore():
    """
    Unit test for getWordScore
    """
    failure=False
    # dictionary of words and scores
    words = {("", 7):0, ("it", 7):4, ("was", 7):18, ("scored", 7):54, ("waybill", 7):155, 
    ("outgnaw", 7):127, ("fork", 7):44, ("fork", 4):94}
    for (word, n) in words.keys():
        score = getWordScore(word, n)
        if score != words[(word, n)]:
            print "FAILURE: test_getWordScore()"
            print "\tExpected", words[(word, n)], "points but got '" \
            + str(score) + "' for word '" + word + "', n=" + str(n)
            failure=True
    if not failure:
        print "SUCCESS: test_getWordScore()"

wordList = loadWords()
print "----------------------------------------------------------------------"
print "Testing getWordScore..."
test_getWordScore()

words.txt位于wods.txt in this zip

我想测试getWordScore(),但我得到了 NameError: global name 'wordList' is not defined

3 个答案:

答案 0 :(得分:0)

您需要在wordList中定义getWordScore

def getWordScore(word, n):
        score = 0
        bonus = 50
        wordList = loadWords() # create wordList
        if word in wordList:

或者将wordList作为参数并将其传递给:

def getWordScore(WordList, word, n):

ps4a.py代码有效,因为如果运行脚本本身就会创建wordList,因此它存在于全局命名空间中。

运行代码的hack是使用模块添加wordList:

def test_getWordScore():
    """
    Unit test for getWordScore
    """
    failure=False
    # dictionary of words and scores
    words = {("", 7):0, ("it", 7):4, ("was", 7):18, ("scored", 7):54, ("waybill", 7):155,
    ("outgnaw", 7):127, ("fork", 7):44, ("fork", 4):94}
    for (word, n) in words.keys():
        score = getWordScore(word, n)
        if score != words[(word, n)]:
            print "FAILURE: test_getWordScore()"
            print "\tExpected", words[(word, n)], "points but got '" \
            + str(score) + "' for word '" + word + "', n=" + str(n)
            failure=True
    if not failure:
        print "SUCCESS: test_getWordScore()"

import ps4a
ps4a.wordList = loadWords()

print "----------------------------------------------------------------------"
print "Testing getWordScore..."
test_getWordScore()

或使用__builtin__

import __builtin__
__builtin__.wordList = loadWords()

全局变量仅在创建它们的模块中是全局变量。

答案 1 :(得分:-1)

添加行,

global wordList 在你想要使用它的函数中。

答案 2 :(得分:-1)

您可以使用global关键字来访问当前函数范围之外的变量:

def getWordScore(word, n):
    global worldList