I am very new to Python and have no idea about how to write a python loop to do selections for ArcGIS. I already finished writing selection codes with different conditions. Is there anyone helping me revise my codes with a python loop?
import arcpy
arcpy.env.workspace = "D:/STAR/STARproject.gdb"
arcpy.MakeFeatureLayer_management('wqi_Conshp_clip27171','wqi_Conshp_clip27171')
#Select level 1 gridcode<=14.3
selection1 = '"gridcode"<=14.3'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection1)
arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel1',[["Shape_Area","sum"]])
#summarize the selected features
arcpy.AddField_management('stats27171wqi_Conlevel1','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel1','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')
#Sum_Area27171 is a variable and already defined in the workspace
#select level 2 14.3<gridcode<=25.6
selection2 = '"gridcode">14.3 AND "gridcode"<=28.6'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection2)
arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel2',[["Shape_Area","sum"]])
arcpy.AddField_management('stats27171wqi_Conlevel2','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel2','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')
#select level 3 28.6<gridcode<=42.9
selection3 = '"gridcode">28.6 AND "gridcode"<=42.9'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection3)
arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel3',[["Shape_Area","sum"]])
arcpy.AddField_management('stats27171wqi_Conlevel3','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel3','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')
#select level 4 42.9<gridcode<=57.2
selection4 = '"gridcode">42.9 AND "gridcode"<=57.2'
arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection4)
arcpy.Statistics_analysis('wqi_Conshp_clip27171','stats27171wqi_Conlevel4',[["Shape_Area","sum"]])
arcpy.AddField_management('stats27171wqi_Conlevel4','rate','DOUBLE')
arcpy.CalculateField_management('stats27171wqi_Conlevel4','rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')
#merge these results
arcpy.Merge_management(['stats27171wqi_Conlevel1','stats27171wqi_Conlevel2','stats27171wqi_Conlevel3',
'stats27171wqi_Conlevel4'],'stats27171wqi_ConMerge')
As you can see, there are four conditions above. Actually, I have another three similar conditions. I am wondering how to combine these selections together with a loop in python to make the work as simple as possible.