【问题标题】:python unboundLocalError whypython unboundLocalError 为什么
【发布时间】:2015-02-10 18:59:01
【问题描述】:
import os

def createFile():
    if os.path.exists("highscores.txt") == False:
        myFile = open("highscores.txt","w")
    myFile.close()

def inputInt():
    number = input(str("please input your score "))

    try:
        return int(number)
    except:
        print ("this is not an acceptable input, please try again")
        inputInt()

def addScore():

    name = input("Please enter the name you wish to add")
    score = inputInt()
    messages = "thank you"

    '''open the highscores line and read in all the lines to a list called scorelist.
    then close the file'''
    scoresFile = open("highscores.txt","r")
    scoresList = scoresFile.readlines()
    scoresFile.close()

    #check each line in the scoresList list
    for i in range(0,len(scoresList) ):

        #check to see if the name is in the line
        if name in scoresList[i]:

            #if it is then strip the name from the text. this should leave theb score
            tempscore = scoresList[i].replace(name,"")

            #if the score is higher then add it to the list
            if int(tempscore)<score:
                message = "Score updated"
                scoresList[i] = (name + str(score))

                #write the scores back to the file
                scoresFile = open("highscores.txt","w")
                for line in scoresList:
                    scoresFile.write(line + "\n")
                scoresFile.close()

                #no need to continue so break
                break
            else:
                #message as score too low
                message= "score too low. not updated"

    if message("Score updated"):
        message = "New score added"
        scoresFile = open("highscores.txt","a")
        scoresFile.write(name + str(score) + "\n")
        scoresFile.close()
    print (message) 

addScore()

上面是代码。显示的错误是:

Traceback (most recent call last):
File "E:\Computer Science\python code\highScores\highscores1.py", line 66, in <module>
addScore()
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore

    if message("Score updated"):
UnboundLocalError: local variable 'message' referenced before assignment

【问题讨论】:

  • 向您的问题添加更多详细信息,解释您的代码以及您如何得到错误,而不仅仅是代码。

标签: python scope


【解决方案1】:

(1) 您指的是message,当scoresList[i] 中没有names 时,它是未定义的。放一个

message = ""

for 循环之前的行。我不知道你的实际意图,所以这将使错误消失,但请检查逻辑是否仍然正确。

(2) 你做的比较不正确。你应该写

if message == "Score updated":

而不是

if message("Score updated"):

【讨论】:

  • 最后两行:if message("Score updated"): ` message = "New score added"` 我假设你想要message == 'Score updated'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
相关资源
最近更新 更多