在 Python 中使用函数外的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3905437/
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
Using a variable outside of function in Python
提问by Fergus Barker
A really simple question, and I'm sure I knew it but must have forgotten
一个非常简单的问题,我确定我知道但一定忘记了
When running this code:
运行此代码时:
x = 0
def run_5():
print "5 minutes later"
x += 5
print x, "minutes since start"
run_5()
print x
I get x isn't defined. How can I have x used in the function and effected outside of it?
我得到 x 未定义。我怎样才能在函数中使用 x 并在函数之外生效?
采纳答案by ghostdog74
Just return a value ?
只返回一个值?
x = 0
def run_5():
print "5 minutes later"
x += 5
return x
x=run_5()
print x
回答by Daniel Roseman
Put global xat the start of the function.
放在global x函数的开头。
However, you should consider if you really need this - it would be better to return the value from the function.
但是,您应该考虑是否真的需要这个 - 最好从函数返回值。
回答by eje211
Just to make sure, the x that is not defined is the one on line 4, not the one on the last line.
只是为了确保,未定义的 x 是第 4 行的 x,而不是最后一行的 x。
The x outside the function is still there and unaffected. It's the one inside that can't have anything added to it because, as far as Python is concerned, it does not exist when you try to apply the += operator to it.
函数外的 x 仍然存在且不受影响。它是内部不能添加任何内容的那个,因为就 Python 而言,当您尝试将 += 运算符应用于它时,它不存在。
回答by Junaid
I think you need to define a variable outside the function, if you want to assign it a return value from the function.
我认为你需要在函数外定义一个变量,如果你想为它分配一个函数的返回值。
The name of the variable can be different than the name in function as it is just holding it
变量的名称可以与函数中的名称不同,因为它只是保存它

