简体   繁体   中英

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)

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM