问题
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