2

I need to access variable from outside of if-condition when the variable is created inside the if-condition in python. The variable types which are inside if-condition are test is <type, str> and vn is <type, instance>.

I have tried the below way but it has not worked for me.

In the below code I need to access vn and test variables

for DO in range(count) :
    atnnames = doc.getElementsByTagName("atnId")[DO]
    atn = atnnames.childNodes[0].nodeValue
    if atn == line[0]:
        vn = doc.getElementsByTagName("vn")[DO]
        vncontent = vn.childNodes[0].nodeValue
        y = vncontent.encode('utf-8')
       # print y
        if '-' in y:
            slt = (int(y.split('-')[0][-1]) + 1)
            test = y.replace(y.split('-')[0][-1], str(slt))
       #     print test
        else:
            slt = (int(y.split('.')[-1]) + 1)
            test = y.replace(y.split('.')[-1], str(slt))
       #     print test
    else:
        #print test
        vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

The error I'm getting when I run the above code is

UnboundLocalError: local variable 'test' referenced before assignment

I tried by defining the variables as None before for loop.

and It is throwing below error. AttributeError: 'NoneType' object has no attribute 'firstChild'

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
moong
  • 73
  • 1
  • 1
  • 9
  • you have to change the scope of the vn variable and define it before for loop – sahasrara62 Feb 11 '19 at 12:01
  • 1
    Why can you not define these variables before the if-else statement? – Glazbee Feb 11 '19 at 12:01
  • you simply can't access that. either you define same indent level as `if` loop or define global depends on your case – Nihal Feb 11 '19 at 12:03
  • 3
    this is nothing to do with variable scope, since Python has function-based scope, not block-based. (In other words, a loop or `if` statement does not define a scope, unlike many other languages.) The issue is that you're referencing a `test` variable in your `else` block that is only defined in the corresponding `if`. – Robin Zigmond Feb 11 '19 at 12:03

2 Answers2

3

define the variable before the if block with None, then update it in the if block. Consider the following:

y = None
x = 1
print(y)
if x == 1:
    y = "d"
else:
    y = 12
print(y)
Maged Saeed
  • 1,784
  • 2
  • 16
  • 35
0

Your problem appears to be the fact that you are referencing a variable outside of its scope. Essentially what is happening is in your if statement you are creating a variable exclusively for use within the if scope. Effectively when you have said print vn.firstChild.nodeValue you can also imagine it as being any other variable such as print undefinedVar. What is occuring is your are referencing (calling) upon the variable before it has even been defined.

However, no worries here since this is very easy to fix. What we can do is simply create your vn and test variables outside of the if scope, hence inside your actual method by doing the following:

vn = None
test = None

for DO in range(count) :
    atnnames = doc.getElementsByTagName("atnId")[DO]
    atn = atnnames.childNodes[0].nodeValue
    if atn == line[0]:
        vn = doc.getElementsByTagName("vn")[DO]
        vncontent = vn.childNodes[0].nodeValue
        y = vncontent.encode('utf-8')
       # print y
        if '-' in y:
            slt = (int(y.split('-')[0][-1]) + 1)
            test = y.replace(y.split('-')[0][-1], str(slt))
       #     print test
        else:
            slt = (int(y.split('.')[-1]) + 1)
            test = y.replace(y.split('.')[-1], str(slt))
       #     print test
    else:
        #print test
        vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

This basically just creates an empty variable in the outermost scope. I've set the values to None since they get defined once your for loop runs. So what happens now is you have a variable which has been declared outside, and is None at the start, but as you run your for loop you are not creating a temporary variable just inside the if statement, but you are actually changing the value of

aaaakshat
  • 809
  • 10
  • 19
  • I'm getting the error when I do that change... ```AttributeError: 'NoneType' object has no attribute 'firstChild'``` – moong Feb 11 '19 at 14:12
  • The NoneType means that you're still dealing with an empty vn variable. I would try debugging by changing the last print statement to just `print vn` and if this returns none then it means the code is working but there is some problem in your assignment logic. Are you sure that the `atnnames` are being defined correctly? – aaaakshat Feb 12 '19 at 23:31