[英]Python Get variable outside the loop
I have a python code ,i need to get its value outside the for loop and if statements and use the variable further:我有一个 python 代码,我需要在 for 循环和 if 语句之外获取它的值并进一步使用该变量:
My code:我的代码:
with open('text','r') as f:
for line in f.readlines():
if 'hi' in line
a='hello'
print a #variable requires outside the loop
But i get Nameerror: 'a' is not defined
但我得到
Nameerror: 'a' is not defined
The error message means you never assigned to a
(ie the if
condition never evaluated to True
).错误消息意味着您从未分配给
a
(即if
条件从未评估为True
)。
To handle this more gracefully, you should assign a default value to a
before the loop:为了更优雅地处理这个问题,您应该在循环之前为
a
分配一个默认值:
a = None
with open('test', 'r') as f:
...
You can then check if it's None
after the loop:然后,您可以在循环后检查它是否为
None
:
if a is not None:
...
You may also try:您也可以尝试:
try:
print a
except NameError:
print 'Failed to set "a"'
EDIT: It simultaneously solves the problem of not printing a , if you did not find what you were looking for编辑:它同时解决了不打印a的问题,如果你没有找到你要找的东西
The other answers here are correct—you need to guarantee that a
has been assigned a value before you try to print it.这里的其他答案是正确的 - 在尝试打印之前,您需要确保
a
已被分配一个值。 However, none of the other answers mentioned Python's for ... else
construct , which I think is exactly what you need here:但是,其他答案都没有提到Python 的
for ... else
构造,我认为这正是您在这里所需要的:
with open('text','r') as f:
for line in f.readlines():
if 'hi' in line:
a='hello'
break
else:
a='value not found'
print a #variable requires outside the loop
The else
clause is only run if the for
loop finishes its last iteration without break
-ing. else
子句仅在for
循环在没有break
情况下完成其最后一次迭代时才运行。
This construct seems unique to Python in my experience.根据我的经验,这种构造似乎是 Python 独有的。 It can be easily implemented in languages that support
goto
, but Python is the only language I know of with a built-in construct specifically for this.它可以在支持
goto
语言中轻松实现,但 Python 是我所知道的唯一一种具有专门为此内置结构的语言。 If you know of another such language, please leave a comment and enlighten me!如果您知道另一种这样的语言,请发表评论并启发我!
只需定义a=null
或a=0
成为全局变量,您可以在代码中的任何位置访问 a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.