如何在函数中更改变量值?

时间:2020-06-10 10:38:43

标签: python function return

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

这是我的代码,运行它时不会发生任何错误,但是当返回“ score”变量时,值重置为0,为什么? (分数首先在第一个函数上方定义,无法放入)

1 个答案:

答案 0 :(得分:1)

Q1函数返回结果,但是您没有将结果保存到变量中。 做这样的事情:

score = Q1(score)
print(score)

或者,直接打印返回值:

print(Q1(score))