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'
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
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)