简体   繁体   English

如何从 function 中更改变量值?

[英]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”变量时,值被重置为0,为什么? (Score is first defined above the first function, couldn't fit it in) (分数首先定义在第一个function上面,放不下)

The Q1 function returns the result but you didn't save the result to a variable. Q1 function 返回结果,但您没有将结果保存到变量中。 Do something like this:做这样的事情:

score = Q1(score)
print(score)

Alternatively, directly print the returned value:或者,直接打印返回值:

print(Q1(score))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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