7

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

4
  • 1
    you have to set the variable a outside the loop Commented Aug 20, 2014 at 13:48
  • 2
    a = None or a = "" before with line. Commented Aug 20, 2014 at 13:49
  • 1
    You missed colon in the if line. Commented Aug 20, 2014 at 13:50
  • @Murillio4 Not necessarily; there's only one scope in the posted code, but a is not guaranteed to be set by the code. Commented Aug 20, 2014 at 13:53

4 Answers 4

11

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:
   ...
Sign up to request clarification or add additional context in comments.

1 Comment

great but i dont want to print if its None what should i do for that?
3

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

Comments

2

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!

Comments

-2

just define a=null or a=0 so a become global variable and you can access a in anywhere in your code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.