I have a python code ,i need to get its value outside the for loop and if statements and use the variable further:
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
The error message means you never assigned to a
(ie the if
condition never evaluated to True
).
To handle this more gracefully, you should assign a default value to a
before the loop:
a = None
with open('test', 'r') as f:
...
You can then check if it's None
after the loop:
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
The other answers here are correct—you need to guarantee that a
has been assigned a value before you try to print it. However, none of the other answers mentioned Python's for ... else
construct , which I think is exactly what you need here:
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.
This construct seems unique to Python in my experience. 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. If you know of another such language, please leave a comment and enlighten me!
只需定义a=null
或a=0
成为全局变量,您可以在代码中的任何位置访问 a
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.