0

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
1

You would need to initialize the height variable before calling it in your loop. As it is now, the if condition is never evaluated to true, 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.

height = 0
for feat in layerbld.getFeatures():
  for f in layer.getFeatures():
     if feat['CR_EDF_UUI']==f['CR_EDF_UUI'] and abs(feat['maxUN_VO_1']-f['Shape_Area']) < 0.0001:
       height=f['UN_VOL_AV']
     else:
       pass
  print height
  • Thanks JGH, now it works! Regarding your interesting consideration about second code, since the feat['maxUN_VO_1'] field was created based on the join by position algorithm in qgis, asking for statistics and in particular for the maximum values, actually I thought that the new value would have been like "pasted" and not calculated (creating some smallest decimal difference)...that's why I put an =. So, thank you for having clarified also this! – FedericaZ Feb 21 '18 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.