How do you change a variable in a function to then be used in the main code?
<p>I am quite new to Python and I am having some trouble figuring out the following:</p>

<pre><code>import random
import sys

print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge &lt; 11:
    print("This quiz is not for your age.")
    sys.exit(0)
else :
    print("Great! Let's begin.\n")

quizQuestions = ["9(3+8)", "7+9*8", "(9+13)(9-5)", "50*25%", "104-4+5*20"]
quizAnswers = ["99", "79", "88", "12.5", "0"]
quizSync = list(zip(quizQuestions, quizAnswers))
random.shuffle(quizSync)
quizQuestions, quizAnswers = zip( * quizSync)
questionNumber = 1
quizScore = 0

def displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore):
    print("Question " + str(questionNumber) + ": " + quizQuestions[questionNumber - 1] + "\n")
    questionAnswer = str(input())
    if questionAnswer == quizAnswers[questionNumber - 1]:
        print("\nCorrect!\n")
        quizScore += 1
    else :
        print("\nIncorrect! The answer is: " + quizAnswers[questionNumber - 1] + "\n")

while questionNumber &lt; 6:
    displayQuestion(quizQuestions, quizAnswers, questionNumber, quizScore)
    questionNumber += 1

print("You have a total score of: "+str(quizScore))
</code></pre>

<p>I would like the variable "quizScore" in the function "displayQuestion" to increase by one if the player gets a question right. However, after the quiz is finished, the print function at the end always prints the score is 0 even if the player gets questions right.</p>

<p>You have to declare it as a global variable inside the function so that it can modify the variable in the global scope</p>

<pre><code>def displayQuestion(quizQuestions, quizAnswers, questionNumber):
    global quizScore    
    ...
    quizScore += 1
</code></pre>

<p>That being said, you should generally avoid global variables if you can and try to redesign your program to either pass the variables along as arguments and return values, or use a class to encapsulate the data.</p>

python function variables