Python 向函数内的变量添加 +1
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18893445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding +1 to a variable inside a function
提问by user2790972
So basically I have no idea what is wrong with this small piece of code, and it seems like I can't find a way to make it work.
所以基本上我不知道这小段代码有什么问题,似乎我找不到让它工作的方法。
points = 0
def test():
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return;
test()
The error I get is:
我得到的错误是:
UnboundLocalError: local variable 'points' referenced before assignment
Note: I can't place the "points = 0" inside the function, because I will repeat it many times, so it would always set the points back to 0 first. I am completely stuck, any help would be appreciated!
注意:我不能把“points = 0”放在函数里面,因为我会重复很多次,所以它总是先把points设置回0。我完全被困住了,任何帮助将不胜感激!
采纳答案by user2722968
points
is not within the function's scope. You can grab a reference to the variable by using nonlocal:
points
不在函数的范围内。您可以使用nonlocal获取对变量的引用:
points = 0
def test():
nonlocal points
points += 1
If points
inside test()
should refer to the outermost (module) scope, use global:
如果points
insidetest()
应该引用最外层(模块)范围,请使用global:
points = 0
def test():
global points
points += 1
回答by Michael Kazarian
Move points into test:
将点移入测试:
def test():
points = 0
addpoint = raw_input ("type ""add"" to add a point")
...
or use global statement, but it is bad practice. But better way it move points to parameters:
或使用global statement,但这是不好的做法。但更好的方法是将点移动到参数:
def test(points=0):
addpoint = raw_input ("type ""add"" to add a point")
...
回答by Xeun
You could also pass points to the function: Small example:
您还可以将点传递给函数:小例子:
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