Thomas Wade
Thomas Wade

Reputation: 3

How to change a variable value from within a function?

def Q1(score): #defines the first question
    print ("\n\n1) Question")
    print ("\nA) Option.")
    print ("\nB) Option")
    print ("\nC) Option.")

    ans = input("\nIs it A, B or C? ") #asks for the answer

    if ans.upper() == "B": #makes it uppercase if they entered lowercase
         print ("Correct!")
         score += 1 #adds one to the score
         return (score) #returns the score

Q1(score) #function is called
print (score) #score is printed

This is my code, no errors occur when I run it but when the "score" variable is returned the value is reset to 0, why? (Score is first defined above the first function, couldn't fit it in)

Upvotes: 0

Views: 57

Answers (1)

James Gatz
James Gatz

Reputation: 36

The Q1 function returns the result but you didn't save the result to a variable. Do something like this:

score = Q1(score)
print(score)

Alternatively, directly print the returned value:

print(Q1(score))

Upvotes: 1

Related Questions