How do I use a variable so that it is inside and outside of a function

我只是一个虾纸丫 提交于 2019-12-13 02:58:17

问题


I would like to know how I can use a variable in a function but then outside of the function as well. Here is a part of my code which is supposed to add 1 to the score when the answer is correct, then print out the overall score afterwards (there is more than one function so I need to the score to be outside of the function):

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

As you can see, I have tried to use arguments however the code still returns the score as 0 at the end no matter if the person has got the answer right.


回答1:


Return score from the function and assign it back to 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, ".")


来源:https://stackoverflow.com/questions/36186687/how-do-i-use-a-variable-so-that-it-is-inside-and-outside-of-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!