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
(i.e. 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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With