If-then-else

3619
16
01-07-2016 11:11 AM
CCWeedcontrol
Occasional Contributor III

I need help setting up an if-than-else within a if-else statement. I need the code i need to check if selected features has any text inside the AddressID field if it does have any text inside the field i need it to by pass the with arcpy.da.SearchCursor and the with arcpy.da.UpdateCursor and move on to the next process. if doesn't have any text inside the field i need it to preform the with arcpy.da.SearchCursor and the with arcpy.da.UpdateCursor. I would appreciate any help.

  1. import arcpy, os 
  2. from arcpy import env 
  3. env.workspace = r"C:\temp\python\test.gdb" 
  4.  
  5. arcpy.env.qualifiedFieldNames = False         
  6. arcpy.env.overwriteOutput = True   
  7.  
  8. BldSelection = "BuildingFootprints"          
  9. Bld = arcpy.env.workspace + os.sep + "BuildingFootprints" #target point feature class   
  10.    
  11. BldCount = int(arcpy.GetCount_management(Bld).getOutput(0))   
  12.    
  13. dsc = arcpy.Describe(BldSelection)    
  14. selection_set = dsc.FIDSet            
  15. if len(selection_set) == 0:          
  16.     print "There are no features selected"     
  17.                 
  18. elif BldCount >= 1:   
  19.     #Gets the highest AddressID and calculates new point to assign new highest AddressID   
  20.     Bld_list = []         
  21.     with arcpy.da.SearchCursor(Bld, ["Bld_ID"]) as cursor:         
  22.         for row in cursor: 
  23.             try:         
  24.                 if "Bld" in row[0]: 
  25.                      
  26.                     Bld_list.append(int(row[0].strip("Bld")))            
  27.             except TypeError:         
  28.                 pass                 
  29.     del cursor         
  30.  
  31.     print Bld_list 
  32.          
  33.     Bld_list.sort()         
  34.     Bld_ID = Bld_list[-1] + 1         
  35.        
  36.    
  37.     with arcpy.da.UpdateCursor(BldSelection, "Bld_ID") as rows:          
  38.         for row in rows:             
  39.             row[0] = 'Bld' + str(Bld_ID) 
  40.             Bld_ID += 1                     
  41.             rows.updateRow(row)     
  42.         del row          
  43.         del rows  
0 Kudos
16 Replies
WesMiller
Regular Contributor III

Why not use Make Feature Layer—Help | ArcGIS for Desktop  and remove those that have data before you start your cursor.

MakeFeatureLayer_management (in_features, out_layer, "Field" > '')

CCWeedcontrol
Occasional Contributor III

I am not sure i follow, add MakeFeatureLayer_management (in_features, out_layer, "Field" > '') in between lines 20 & 21?

0 Kudos
WesMiller
Regular Contributor III

Something similar to below

import arcpy, os    
from arcpy import env    
env.workspace = r"C:\temp\python\test.gdb"    
    
arcpy.env.qualifiedFieldNames = False            
arcpy.env.overwriteOutput = True      
    
BldSelection = "BuildingFootprints"             
Bld = arcpy.env.workspace + os.sep + "BuildingFootprints" #target point feature class      


bldlyr = arcpy.MakeFeatureLayer_management(Bld,"Building_layer","AddressID > ''")
BldCount = int(arcpy.GetCount_management(bldlyr).getOutput(0))      
      
dsc = arcpy.Describe(BldSelection)       
selection_set = dsc.FIDSet               
if len(selection_set) == 0:             
    print "There are no features selected"        
                   
elif BldCount >= 1:      
    #Gets the highest AddressID and calculates new point to assign new highest AddressID      
    Bld_list = []            
    with arcpy.da.SearchCursor(bldlyr, ["Bld_ID"]) as cursor:            
        for row in cursor:    
            try:            
                if "Bld" in row[0]:    
                        
                    Bld_list.append(int(row[0].strip("Bld")))               
            except TypeError:            
                pass                    
    del cursor            
    
    print Bld_list    
            
    Bld_list.sort()            
    Bld_ID = Bld_list[-1] + 1            
          
      
    with arcpy.da.UpdateCursor(BldSelection, "Bld_ID") as rows:             
        for row in rows:                
            row[0] = 'Bld' + str(Bld_ID)    
            Bld_ID += 1                        
            rows.updateRow(row)        
        del row             
        del rows
0 Kudos
CCWeedcontrol
Occasional Contributor III

Wes suggestion is interesting, i never thought of doing that. I made the change to the code but the Bld_ID for the selected feature doesn't get populated.

I will still like to see how to use the if-ten-else

import arcpy, os  
from arcpy import env  
arcpy.env.workspace = r"Database Servers\DSD15_SQLEXPRESS.gds\CCAPTEST (VERSION:dbo.DEFAULT)"  
  
arcpy.env.qualifiedFieldNames = False          
arcpy.env.overwriteOutput = True    
  
BldSelection = "CCAPTEST.DBO.BldTaxChar"           
Bld = arcpy.env.workspace + os.sep + "CCAPTEST.DBO.BldTaxChar" #target point feature class

    
bldlyr = arcpy.MakeFeatureLayer_management(Bld,"Building_layer","AddressID > ''")  
BldCount = int(arcpy.GetCount_management(bldlyr).getOutput(0))
   
    
dsc = arcpy.Describe(BldSelection)     
selection_set = dsc.FIDSet

if len(selection_set) == 0:           
    print "There are no features selected"        
                 
elif BldCount >= 1:


    # Start an edit session. Must provide the worksapce.
    edit = arcpy.da.Editor(arcpy.env.workspace)

    # Edit session is started without an undo/redo stack for versioned data
    #  (for second argument, use False for unversioned data)
    edit.startEditing(True)

    # Start an edit operation
    edit.startOperation()
    
    #Gets the highest AddressID and calculates new point to assign new highest AddressID    
    Bld_list = []          
    with arcpy.da.SearchCursor(bldlyr, ["Bld_ID"]) as cursor:          
        for row in cursor:  
            try:          
                if "Bld" in row[0]:  
                      
                    Bld_list.append(int(row[0].strip("Bld")))             
            except TypeError:          
                pass                  
    del cursor          
  
    print Bld_list  
          
    Bld_list.sort()          
    Bld_ID = Bld_list[-1] + 1          
        
    
    with arcpy.da.UpdateCursor(BldSelection, "Bld_ID") as rows:           
        for row in rows:              
            row[0] = 'Bld%05d' %Bld_ID 
            Bld_ID += 1                      
            rows.updateRow(row)      
        del row           
        del rows
    # Stop the edit operation.
    edit.stopOperation()

    # Stop the edit session and save the changes
    #edit.stopEditing(True)
    if arcpy.Exists(parcel_lyr): arcpy.Delete_management(parcel_lyr)
    arcpy.RefreshActiveView() 
0 Kudos
WesMiller
Regular Contributor III

See below

condition = 1
if condition == 1:
    print 'yes it is'
else:
    print "no it isn't" 

Edit

This may be a better example for what you are trying to do.

import arcpy
fc = 'Your feature class'
field = 'your field'
with arcpy.da.SearchCursor(fc, [field]) as cursor:
    for row in cursor:
        if row[0] >'':
            print row[0]
        else:
            print 'update row'
CCWeedcontrol
Occasional Contributor III

ok, for some reason i was thinking i had to put an if-then-else statement after "elif BldCount >= 1: " line 21

after making the following adjustment, the selected features "Bld_ID" field still doesn't populate when i run the following code...? I get no error.

Edit:

I had things that i need to change. the code is now working, i think. i will do testing.

Thanks Wes!

import arcpy, os  
from arcpy import env  
arcpy.env.workspace = r"Database Servers\DSD15_SQLEXPRESS.gds\CCAPTEST (VERSION:dbo.DEFAULT)"  
  
arcpy.env.qualifiedFieldNames = False          
arcpy.env.overwriteOutput = True    
  
BldSelection = "CCAPTEST.DBO.BldTaxChar"           
Bld = arcpy.env.workspace + os.sep + "CCAPTEST.DBO.BldTaxChar" #target point feature class

BldCount = int(arcpy.GetCount_management(Bld).getOutput(0))

dsc = arcpy.Describe(BldSelection)     
selection_set = dsc.FIDSet

if len(selection_set) == 0:           
    print "There are no features selected"        
                 
elif BldCount >= 1:


    # Start an edit session. Must provide the worksapce.
    edit = arcpy.da.Editor(arcpy.env.workspace)

    # Edit session is started without an undo/redo stack for versioned data
    #  (for second argument, use False for unversioned data)
    edit.startEditing(True)

    # Start an edit operation
    edit.startOperation()
    
    #Gets the highest AddressID and calculates new point to assign new highest AddressID    

    with arcpy.da.SearchCursor(BldSelection , "Bld_ID") as cursor:  
        for row in cursor:  
            if row[0] >'':  
    
                Bld_list = []          
                with arcpy.da.SearchCursor(Bld, ["Bld_ID"]) as cursor:          
                    for row in cursor:  
                        try:          
                            if "Bld" in row[0]:  
                                  
                                Bld_list.append(int(row[0].strip("Bld")))             
                        except TypeError:          
                            pass                  
                del cursor          
              
                print Bld_list  
                      
                Bld_list.sort()          
                Bld_ID = Bld_list[-1] + 1          
                    
                
                with arcpy.da.UpdateCursor(BldSelection, "Bld_ID") as rows:           
                    for row in rows:              
                        row[0] = 'Bld%05d' %Bld_ID 
                        Bld_ID += 1                      
                        rows.updateRow(row)      
                    del row           
                    del rows

            else: #other process sptial join
        
                edit.stopOperation()
    # Stop the edit operation.
    # Stop the edit session and save the changes
    #edit.stopEditing(True)
    #if arcpy.Exists(parcel_lyr): arcpy.Delete_management(parcel_lyr)
    arcpy.RefreshActiveView() 
0 Kudos
CCWeedcontrol
Occasional Contributor III

spoke to soon the code is not working, no errors, field Bld_ID doesn't get populated

0 Kudos
CCWeedcontrol
Occasional Contributor III

I just noticed that some of the selected features are "NULL", would that affect line 36?

0 Kudos
WesMiller
Regular Contributor III

Null < ''

0 Kudos