简体   繁体   English

UnboundLocalError:赋值前引用了局部变量“Score”

[英]UnboundLocalError: local variable 'Score' referenced before assignment

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()

I know that some of the variables set here are not needed, but I'll fix them in the future;我知道这里设置的一些变量不是必需的,但我将来会修复它们; all I want to know is how to fix this error message:我只想知道如何修复此错误消息:

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
>>> 

I have tried global Score but then it says;我已经尝试过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

So now I am out of options.所以现在我别无选择。

Variables inside a function are of local scope.函数内的变量是local作用域。 You can do like this(declare variable inside a function )你可以这样做(在函数内声明变量)

def Quiz():
    Score = 0

OR use global (not recommended)或使用global (不推荐)

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

UPDATE更新

Since you defined a function inside a function,既然你在函数内部定义了一个函数,

def Q1():  
    global Score

i tried to do what you did but it did not work so i took that same idea and put global Score after def Q1(): instead and it worked..我试图做你所做的但它没有奏效所以我采取了同样的想法并将 global Score 放在 def Q1(): 之后,它起作用了..

def Q1():  
    global Score

and thx very much 4 ur help :)非常感谢 4 你的帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “UnboundLocalError:赋值前引用了局部变量‘score’” - “UnboundLocalError: local variable 'score' referenced before assignment” Python 错误:UnboundLocalError:赋值前引用了局部变量“score1” - Python error: UnboundLocalError: local variable 'score1' referenced before assignment UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment UnboundLocalError:分配前已引用局部变量“ Counter” - UnboundLocalError: local variable 'Counter' referenced before assignment UnBoundLocalError:赋值之前引用的局部变量(Python) - UnBoundLocalError: local variable referenced before assignment (Python) UnboundLocalError:分配前已引用局部变量“ strdate” - UnboundLocalError: local variable 'strdate' referenced before assignment UnboundLocalError:赋值之前引用了局部变量“ key” - UnboundLocalError: local variable 'key' referenced before assignment unboundLocalError:赋值前引用了局部变量“loopback” - unboundLocalError: local variable 'loopback' referenced before assignment UnboundLocalError:分配前已引用局部变量“ endProgram” - UnboundLocalError: local variable 'endProgram' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM