Adding +1 to a variable inside a function
本问题已经有最佳答案,请猛点这里访问。
所以基本上我不知道这段代码出了什么问题,似乎我找不到一种方法让它工作。
1 2 3 4 5 6 7 8 9 10 | points = 0 def test(): addpoint = raw_input ("type""add"" to add a point") if addpoint =="add": points = points + 1 else: print"asd" return; test() |
我得到的错误是:
1 | UnboundLocalError: local variable 'points' referenced before assignment |
注意:我不能将"points=0"放在函数中,因为我会重复多次,所以它总是先将点设置回0。我完全被困住了,任何帮助都会被感激的!
1 2 3 4 | points = 0 def test(): nonlocal points points += 1 |
如果
1 2 3 4 | points = 0 def test(): global points points += 1 |
您还可以将点传递给函数:小例子:
1 2 3 4 5 6 7 8 9 10 11 12 | def test(points): addpoint = raw_input ("type""add"" to add a point") if addpoint =="add": points = points + 1 else: print"asd" return points; if __name__ == '__main__': points = 0 for i in range(10): points = test(points) print points |
将点移动到测试中:
1 2 3 4 | def test(): points = 0 addpoint = raw_input ("type""add"" to add a point") ... |
或者使用全局语句,但这是不好的做法。但更好的方法是将点移动到参数:
1 2 3 | def test(points=0): addpoint = raw_input ("type""add"" to add a point") ... |