错误,即使语法正确吗?

时间:2017-03-13 14:18:30

标签: python python-2.7

我正在编写“编程简介”课程中制作“财富之轮”游戏。我正在努力的步骤表明,你需要询问玩家是否想要“旋转方向盘”或购买元音。在我做出def之前,我已经将变量'money'设置为零,但是当我尝试在定义中引用它时,它说:

line 77, in <module>
r=askSpin()
line 67, in askSpin
if money >= 250:
UnboundLocalError: local variable 'money' referenced before assignment

我目前拥有的代码如下:

import random

names = ["FAMOUS NAMES","jack black","john johns", "donald trump", "filthy frank", "idubbbztv", "john cena"]
places = ["PLACES","rome","home", "maryland", "china", "trump towers", "white house", "reddit"]
categories = [names,places]

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

def displayBoard(missedLetters, correctLetters, secretWord):
    print 'Missed letters:',
    for letter in missedLetters:
        print letter,
    print()

    blanks = '_' * len(secretWord)

    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
    print clue
    for letter in blanks: # show the secret word with spaces in between each letter
        print letter,

    print()

def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
    while True:
        guess = raw_input('Guess a letter:')
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return raw_input().lower().startswith('y')

#gets a puzzle
def getRandomPuzzle(cat):
    return cat[random.randint(1,len(cat)-1)]

print('WHEEL OF FORTUNE')
wheel = [900, 2500, 900, 700, 600, 800, 700, 1000000, 600, 550, 900, 650, 700, 800, 650, 0]
missedLetters = ''
correctLetters = ' '
secretIndex = random.randint(0, len(categories) - 1)
c = categories[secretIndex]
secretWord = getRandomPuzzle(c)
clue = c[0]
global money
money = 0
gameIsDone = False
def askSpin():
    ans = raw_input("Would you like to buy a vowel [b], or would you like to spin? [s]")
    if ans == "b":
        if money >= 250:
            money = money - 250
            guess = guess
        if money < 250:
            guess = raw_input("You have insufficient funds, please guess a letter.")
    return ans.lower().startswith('s')
while True:
    displayBoard( missedLetters, correctLetters, secretWord)

    #give user option to spin
    r=askSpin()
    while not r:
        r=askSpin()
    #spin wheel
    value = wheel[random.randint(0,len(wheel)-1)]
    allowGuess = True #flag remains True unless spin BANKRUPT
    if value == 0:
        print "BANKRUPT!!! Good luck paying off those debts! - You have $0"
        allowGuess = False #do not allow user to guess letter
        money = 0
    else:
        print "You rolled $",value

    # Let the player type in a guess.
    if allowGuess:
        guess = getGuess(missedLetters + correctLetters)

        #if the letter is in the word
        if guess in secretWord:
            correctLetters = correctLetters + guess
            #handle money
            letterCount = secretWord.count(guess) #get num occurrences of guess
            money +=(letterCount*value) #add winnings to money

            #print how many occurrences there are
            intro = "There is"
            outro = ""
            if letterCount>1:
                intro = "There are"
                outro = "'s"
            print intro,letterCount,guess,outro

            # Check if the player has won
            foundAllLetters = True
            for i in range(len(secretWord)):
                if secretWord[i] not in correctLetters:
                    foundAllLetters = False
                    break
            if foundAllLetters:
                print('Yes! The secret word is "' + secretWord + '"! You have won!')
                gameIsDone = True

        else: #the letter is not in the word
            print "There are no", guess + "'s"
            missedLetters = missedLetters + guess
        print "You have $", money
    # Ask the player if they want to play again (but only if the game is done).
    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ' '
            gameIsDone = False
            money = 0 #reset money
            secretIndex = random.randint(0, len(categories) - 1)
            c = categories[secretIndex]
            secretWord = getRandomPuzzle(c)
            clue = c[0]
        else:
            break

如果你能告诉我我做错了什么给了我这个错误,那对我有用。

2 个答案:

答案 0 :(得分:2)

在代码中的随机位置声明global money不会带来任何好处。如果要告诉函数变量是全局变量,则应在函数内声明此global

答案 1 :(得分:1)

global money方法中添加askPin

在函数内声明变量为global意味着这是在全局范围内声明的变量,而不是在此范围内创建新变量。