UnboundLocalError:局部变量'得分'在分配之前引用

时间:2015-10-30 11:23:12

标签: python variables syntax-error local traceback

import time
from random import randint
import sys
import random
Level = 0
ONE = 10
TWO = 20
THREE = 60
FOUR = 100
FIVE = 150
QN = 0
TEN = 10
Zero = 0
Chances = 5
Score = 0
Name = input("What is your name? \n").title()
time.sleep(1)
class_name = input("What class are you in? \n").upper()
time.sleep(1)
print("Welcome!\nTo the Ten Question Quiz {}!!".format(Name))
time.sleep(1)
operation = ['+','-','*']   #holds all of the opperators
RO = random.choice(operation)#chooses a random operator
def Quiz():
    RoG = input(Name+" Please type 'rules' to view the rules or Press 'ANY' key to Continue\n*********************************************************************************************************\n")
    if RoG == "rules":
        time.sleep(1)
        print("*********************************************************************************************************")
        print("*RULES/HOW TO PLAY* \nThere will be 10 Questions for you to answer \nthere WILL be a timer, total time taken to finish the quiz \nYou will be able to choose the Level from 1, 2, 3\n1 = Very Easy, 2 = Easy, 3 = Medium, 4 = Hard, 5 = Very Hard \nYou will only have '5' chances to answer, 'ALL' The 10 Questions.")
        input("Press 'ANY' key to Return to the previous page\n*********************************************************************************************************")
        Quiz()
    else:
        LV = input("Please Choose Your Level From (1, 2, 3, 4, 5)\n")
        if LV == "1":
            Level = ONE
        elif LV == "2":
            Level = TWO
        elif LV == "3":
            Level = THREE
        elif LV == "4":
            Level = FOUR
        elif LV == "5":
            Level = FIVE
        def Timer():
            start_time = time.time()
            def Q1():  
                global Chances
                while Chances > Zero:
                    global QN
                    QN = QN+1
                    if str(QN) == "10":
                        time.sleep(1)
                        print("You have Finished The Ten Question Quiz {} !!".format(Name))
                        time.sleep(1)
                        end_time = time.time()
                        print("Total time taken was %g seconds." % (end_time - start_time))
                        print("Your Score is {} /10".format(Score))
                        Class_name = class_name + ".txt"    #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies
                        file = open(Class_name , 'a')   #opens the file in 'append' mode so you don't delete all the information
                        name = (Name)
                        file.write(str(name + " " + class_name + ", Your score is: " )) #writes the information to the file
                        file.write(str(Score))
                        file.write("/10 Level: ")
                        file.write(str(LV))
                        file.write(", Total time taken was %g seconds." % (end_time - start_time))
                        file.write('\n')
                        file.close()    #safely closes the file to save the information
                        viewscore = input("Do you wish to view previous results for your class:(yes/no) \n").lower()
                        if viewscore == "yes".lower():
                            f = open(Class_name, 'r')
                            file_contents = f.read()
                            print (file_contents)
                            f.close()
                            if input("Press 'Y' to exit \nor press any key to start again.").lower() == "y":
                                sys.exit()
                            else:
                                ex = input("")
                                Quiz()
                        elif viewscore != "yes".lower():
                            if input("Press 'Y' to exit \nor press any key to start again.").lower() == "y":
                                sys.exit()
                            else:
                                ex = input("")
                                Quiz()
                    else:
                        print("Starting Question {}".format(QN))
                        Ran1 = randint(1,Level)
                        Ran11 = randint(1,Level)
                        time.sleep(1)
                        RO = random.choice(operation)    #chooses a random operator
                        Answer1=int(eval(str(Ran1) + RO + str(Ran11)))
                        print ("What is {} {} {}?".format(Ran1, RO, Ran11))
                        if input() == str(Answer1):
                            print("Thats the Correct Answer WELL DONE!")
                            Score = Score+1
                            print("*********************************************************************************************************")
                            Q1()
                        else:
                            Chances = Chances-1
                            print("Wrong!\nThats the wrong answer, you got {} Chance(s)".format(Chances))
                            print("*********************************************************************************************************")
                            Q1()
            Q1()
        Timer()
Quiz()

我知道这里设置的一些变量不需要,但我将来会修复它们;我想知道的是如何修复此错误消息:

Traceback (most recent call last):
  File "N:/IMPORTANT/Assessment2222 - Copyc.py", line 105, in <module>
    Quiz()
  File "N:/IMPORTANT/Assessment2222 - Copyc.py", line 104, in Quiz
    Timer()
  File "N:/IMPORTANT/Assessment2222 - Copyc.py", line 103, in Timer
    Q1()
  File "N:/IMPORTANT/Assessment2222 - Copyc.py", line 95, in Q1
    Score = Score+1
UnboundLocalError: local variable 'Score' referenced before assignment
>>> 

我已经尝试了global Score,但随后它说了;

>>> 
Warning (from warnings module):
  File "N:/IMPORTANT/Assessment2222 - Copyc.py", line 95
    global Score
SyntaxWarning: name 'Score' is used prior to global declaration

所以现在我没有选择。

2 个答案:

答案 0 :(得分:0)

函数内的变量属于local范围。你可以这样做(在函数内声明变量)

def Quiz():
    Score = 0

或使用global(不推荐)

Score = 0
def Quiz():
    global Score
    Score = Score + 1

<强>更新

由于您在函数内定义了一个函数,

def Q1():  
    global Score

答案 1 :(得分:0)

我试着做你做的但是它没有用,所以我采取了同样的想法,并在def Q1()之后放了全球分数:相反,它有效..

def Q1():  
    global Score

和thx非常多4个人的帮助:)