Python初学者 - 我做对了吗?测验与分数
问题描述:
#Quiz answer variables go here!
ca1 = cringe_crew[0]
ca2 = cucks[0]
ca3 = 5
ca4 = cringe_crew[1]
ca5 = 'No'
#Questions
q1 = "Question 1 - Who do we refer to when shouting CODE YELLOW? "
q2 = "Question 2 - Who would you think of if I called him 'Linux Boy': "
q3 = "Question 3 - How many people were there in the original Cringe-Crew back in the days of 2015? "
q4 = "Question 4 - Biggest pseudo Overwatch fan? (top tip: even bought a fucking bag): "
q5 = "Question 5 - Do we miss Luke Slater? "
#a is the raw_input answer
#b is the correct answer needed
#a1-a5 will be separately stored raw_input ANSWERS
#ca1-ca5 are already called as variables and these are the correct answers.
#Score
score = 0
def compare(a, ca):
if a == ca:
score = score + 1
print "That's correct! The answer was %s" % ca
print "Your score is", score
else:
print "%s is not the correct answer - you did not get a point!" % a
return;
#test
a1 = raw_input(q1)
compare(a1, ca1)
a2 = raw_input(q2)
compare(a2, ca2)
a3 = raw_input(q3)
compare(a3, ca3)
a4 = raw_input(q4)
compare(a4, ca4)
a5 = raw_input(q5)
compare(a5, ca5)
嘿家伙,我是全新的python和编码整体,但想开始与一个小测验与分数,虽然我觉得我去完全错误的结构明智,如果我删除了'分数'的代码运行完全正常。如果我有它,出现这种情况:Python初学者 - 我做对了吗?测验与分数
Traceback (most recent call last):
File "ex2.py", line 57, in <module>
compare(a1, ca1)
File "ex2.py", line 46, in compare
score = score + 1
UnboundLocalError: local variable 'score' referenced before assignment
你能给我特别是对如何构建在这样的情况下,代码任何提示?非常感谢!
答
在您的compare()
函数中,在尝试访问它的值之前,您尚未定义您的score
变量。
您应该将它传递给比较函数(将其作为参数添加到函数中),然后将结果返回(首选),或者将其声明为函数内的全局变量(更简单,但不是技术上的最好的方法)。
如
传递参数&返回值的解决方案:
def compare(a, ca, scr):
if a == ca:
scr = scr + 1
print "That's correct! The answer was %s" % ca
print "Your score is", scr
else:
print "%s is not the correct answer - you did not get a point!" % a
return scr ;
# skipping some code here
score = compare(a1, ca1, score)
全局变量的解决方案:
def compare(a, ca):
global score
if a == ca:
score = score + 1
print "That's correct! The answer was %s" % ca
print "Your score is", score
else:
print "%s is not the correct answer - you did not get a point!" % a
return;
否则,在全局范围内score
是一个完全不同的变量为t即使他们具有相同的名称,他也可以在compare
范围内使用score
。
答
在比较功能添加全局语句得分:
def compare(a, ca):
global score
if ca == ca:
# the rest of your code
重复:http://*.com/questions/423379/using-global-variables-in-a-function-other-than -THE-一个是创建的,他们 – qxz