python if语句里面的语法错误

时间:2015-06-23 09:37:14

标签: python if-statement syntax-error

我写了一些代码,但我无法理解为什么pyscripter在if语句中告诉语法错误:

#search for 9 elements
file_writer = open('C:\\PythonProject2\\commands_NUM.txt','w')
for item in data_indices:
    flag= search_object(item,data,obj_value_min,obj_value_max)
        if flag = True:###ERROR
            file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##Here is the syntax error

file_writer.close()

def search_object(pixel,frame,min_val,max_val):
    (obj_y,obj_x) = pixel
    y_center = pixel[0]+1
    x_center = pixel[1]+1
    if(obj_y<=597 and obj_x<=797 ):
        for y in range(0,3):
            for x in range(0,3):
                if((frame[obj_y+y][obj_x+x])<=min_val or(frame[obj_y+y]    [obj_x+x])>=max_val ):
                    return False

return True

3 个答案:

答案 0 :(得分:4)

if语句在for循环中向内缩进。此外,=表示分配使用==代替

for item in data_indices:
    flag= search_object(item,data,obj_value_min,obj_value_max)
    if flag == True:            #here indent this if one step back
          file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n') ##He

答案 1 :(得分:1)

if语句中应该有==

for item in data_indices:
    flag= search_object(item,data,obj_value_min,obj_value_max)
    if flag == True:
        file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n')

答案 2 :(得分:1)

1)将您的search_object功能放在上面 - 在使用前声明它 2)将if flag = True:修复为if flag:
3)修复file_writer.write('frame0: ' + str(item[0]+1)+' ' + str(item[1]+1) + '\n')行缩进 4)函数return True内的search_object也有错误的缩进。解决它。
我建议你看看this question