Function 如何使用变量,使其位于函数的内部和外部
我想知道如何在函数中使用变量,但也可以在函数外使用。 这是我的代码的一部分,当答案正确时,应该在分数上加1,然后打印出总分数(有多个函数,因此我需要将分数设置在函数之外):Function 如何使用变量,使其位于函数的内部和外部,function,variables,if-statement,arguments,python-3.4,Function,Variables,If Statement,Arguments,Python 3.4,我想知道如何在函数中使用变量,但也可以在函数外使用。 这是我的代码的一部分,当答案正确时,应该在分数上加1,然后打印出总分数(有多个函数,因此我需要将分数设置在函数之外): 正如您所看到的,我尝试使用参数,但是代码在最后仍然返回0分,无论这个人的答案是否正确 从函数返回score,并将其分配回score score=0 def Geography(score): #Question 1 qa1= input("What is the capital of England? ")
正如您所看到的,我尝试使用参数,但是代码在最后仍然返回0分,无论这个人的答案是否正确 从函数返回
score
,并将其分配回score
score=0
def Geography(score):
#Question 1
qa1= input("What is the capital of England? ")
if qa1.lower() == ("london"):
print ("Correct you gain 1 point")
score=score+1
else:
print ("Incorrect")
return score
score = Geography(score)
print ("This quiz has ended. Your score is " , score, ".")
这会导致代码自身重复,但仍然表示分数为0。它如何导致代码自身重复?我刚测试过,效果很好。你的代码中有没有更多的东西没有放在问题中?对不起,代码不再重复了,这是我的错。有多个函数,用户必须在其中进行选择,因此在调用函数时,它位于if语句中。
score=0
def Geography(score):
#Question 1
qa1= input("What is the capital of England? ")
if qa1.lower() == ("london"):
print ("Correct you gain 1 point")
score=score+1
else:
print ("Incorrect")
return score
score = Geography(score)
print ("This quiz has ended. Your score is " , score, ".")