如何使用变量使其在函数内部和外部

时间:2016-03-23 19:07:19

标签: function variables if-statement arguments python-3.4

我想知道如何在函数中使用变量,但在函数之外也是如此。 这是我的代码的一部分,当答案是正确的时候应该在分数上加1,然后打印出总得分(有多个函数,所以我需要得分在函数之外):

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

Geography(score)
print ("This quiz has ended. Your score is " , score, ".")

正如你所看到的,我试图使用参数,但无论该人是否得到了正确答案,代码仍然会将得分返回为0。

2 个答案:

答案 0 :(得分:1)

从函数中返回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, ".")

答案 1 :(得分:0)

尝试在变量“score”之前使用“global”并在“def Geography():”函数中再次访问它。此代码应该适用于代码中的所有“def”函数:

global score
score = 0


def Geography():
    # Question 1
    global score
    qa1 = input("What is the capital of England? ")
    if qa1.lower() == ("london"):
        print("Correct you gain 1 point")
        score = score + 1
    else:
        print("Incorrect")


Geography()
print("This quiz has ended. Your score is ", score, ".")