Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 995
adasq raam Avatar asked Dec 20 '22 12:12

adasq raam


1 Answers

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:
   ...
like image 144
NPE Avatar answered Jan 03 '23 09:01

NPE