After importing PyQt4.QtCore,PyQt4.QtGui and processing and after having correctly defined layers, I executed this script in PyQGIS but it returns this error:
Traceback (most recent call last):
File "", line 9, in
NameError: name 'height' is not defined (so it refers to line "print height").
I also failed by checking in previous posts:
like https://stackoverflow.com/questions/20177159/python-nameerror-name-width-is-not-defined or NameError: variable not defined even though set multiple times and other ones but do not fit because different from my case.
Any suggestions?
layerbld.startEditing()
maxh_field=layerbld.dataProvider().fieldNameIndex('MaxHeight')
for feat in layerbld.getFeatures():
for f in layer.getFeatures():
if feat['CR_EDF_UUI']==f['CR_EDF_UUI'] and feat['maxUN_VO_1']==f['Shape_Area']:
height=f['UN_VOL_AV']
else:
pass
print height
layerbld.changeAttributeValue(feat.id(),maxh_field,height)
layerbld.updateFields()
layerbld.commitChanges()
I tried to correct in this way but it returns only null values, that's not possible:
for feat in layerbld.getFeatures():
for f in layer.getFeatures():
if feat['CR_EDF_UUI']==f['CR_EDF_UUI']:
if feat['maxUN_VO_1']==f['Shape_Area']:
height=f['UN_VOL_AV']
else:
height=0
print height
Best Answer
You would need to initialize the
height
variable before calling it in your loop. As it is now, theif
condition is never evaluated totrue
, so the variable is never created and the code fails when you try to print it.Note that it is consistent with the second code in your question. You say it is impossible, but be very careful when comparing floating point values (i.e. with decimals) as what can look the same number can be stored differently, and therefore not be equal. You could check if the difference between the two areas is smaller than a small number.