编写一个函数来在points = 0之后添加点

时间:2016-04-19 18:44:53

标签: python function

我正在写一个函数来找出你赚了多少积分。它应该将点添加到点,但是当我在函数外打印点时,它表示点= 0.这是函数...

points = 0
def correct(points):
        if question >= 0 and question <= 3:
            points = points + 100
            print 'That was a 100 point question.'
        elif question >= 4 and question <= 7:
            points = points + 200
            print 'That was a 200 point question.'
        elif question >= 8 and question <= 11:
            points = points + 300
            print 'That was a 300 point question.'
        else: 
            points = points + 400
            print 'That was a 400 point question.'
        return points


Here is an example of the function in my code.

    if ranswer == random2[question]: #if you get it right
        correct(points)
        print 'Correct! You now have', points, 'points!'

最后,它应该打印我所拥有的点数,但它会打印0。

1 个答案:

答案 0 :(得分:1)

您需要指定points以从correct(points)返回值。

points = correct(points)

整数是Python中的不可变对象。在points内为correct()分配新值时,它与您拥有的原始points不同。现在它指向一个不同的整数对象。这就是您需要在使用points返回值调用代码时更新correct(points)的原因。