lundi 11 février 2019

How to access the variables after if-condition when the variable is defined inside the if-condition in python

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

Aucun commentaire:

Enregistrer un commentaire