How Do I Use A Variable So That It Is Inside And Outside Of A Function
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 ans
Solution 1:
Return score
from the function and assign it back to score
score=0defGeography(score):
#Question 1
qa1= input("What is the capital of England? ")
if qa1.lower() == ("london"):
print ("Correct you gain 1 point")
score=score+1else:
print ("Incorrect")
return score
score = Geography(score)
print ("This quiz has ended. Your score is " , score, ".")
Solution 2:
Try using "global" before variable "score" and access it again in the "def Geography():" function. This code should work for all "def" functions in code:
global score
score = 0defGeography():
# Question 1global score
qa1 = input("What is the capital of England? ")
if qa1.lower() == ("london"):
print("Correct you gain 1 point")
score = score + 1else:
print("Incorrect")
Geography()
print("This quiz has ended. Your score is ", score, ".")
Post a Comment for "How Do I Use A Variable So That It Is Inside And Outside Of A Function"