每次我运行我的程序,在回答完第一个问题后,我都会收到这个消息。我不明白为什么会一直发生这种情况,因为我已经在一切之前创建了分数变量,我不明白为什么会有问题。我该如何解决这个问题?这是我的代码。
score = 0
name = input("Before we start, what would you like me to call you? : ")
def greeting():
print ("Welcome to your Math review quiz,",name)
print("You will have to answer 5 questions")
def quiz1():
q1 = int (input("5 + 5 : "))
if q1 == 10:
print("Correct")
score = score + 1
else :
print ("Incorrect")
q2 = int (input ("5 + 10 : "))
if q2 == 15 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q3 = int (input ("50 + 10 : "))
if q3 == 60 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q4 = int (input ("50 + 50 : "))
if q4 == 100 :
print("Correct")
score = score + 1
else :
print("Incorrect")
greeting()
quiz1()
当你在函数定义中引用一个变量时(方法除外),python会引用本地的可变量。你可以编辑 score
作为一个全局变量,用 global
关键字。
score = 0
name = input("Before we start, what would you like me to call you? : ")
def greeting():
print ("Welcome to your Math review quiz,",name)
print("You will have to answer 5 questions")
def quiz1():
global score # add this line #
q1 = int (input("5 + 5 : "))
if q1 == 10:
print("Correct")
score = score + 1
else :
print ("Incorrect")
q2 = int (input ("5 + 10 : "))
if q2 == 15 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q3 = int (input ("50 + 10 : "))
if q3 == 60 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q4 = int (input ("50 + 50 : "))
if q4 == 100 :
print("Correct")
score = score + 1
else :
print("Incorrect")
greeting()
quiz1()
变量的范围是 score
不在 quiz1
. 因此,我会把它传进去,并以合适的方式返回。
score = 0
name = input("Before we start, what would you like me to call you? : ")
def greeting():
print ("Welcome to your Math review quiz,",name)
print("You will have to answer 5 questions")
def quiz1(score):
q1 = int (input("5 + 5 : "))
if q1 == 10:
print("Correct")
score = score + 1
else :
print ("Incorrect")
q2 = int (input ("5 + 10 : "))
if q2 == 15 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q3 = int (input ("50 + 10 : "))
if q3 == 60 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q4 = int (input ("50 + 50 : "))
if q4 == 100 :
print("Correct")
score = score + 1
else :
print("Incorrect")
return score
greeting()
score = quiz1(score)
使 score
全局性的,添加 global score
在函数的第一行。
这可能有助于
name = input("Before we start, what would you like me to call you? : ")
def greeting():
print ("Welcome to your Math review quiz,",name)
print("You will have to answer 5 questions")
def quiz1():
score = 0
q1 = int (input("5 + 5 : "))
if q1 == 10:
print("Correct")
score = score + 1
else :
print ("Incorrect")
q2 = int (input ("5 + 10 : "))
if q2 == 15 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q3 = int (input ("50 + 10 : "))
if q3 == 60 :
print("Correct")
score = score + 1
else :
print("Incorrect")
q4 = int (input ("50 + 50 : "))
if q4 == 100 :
print("Correct")
score = score + 1
else :
print("Incorrect")
greeting()
quiz1()