Python缩进(for循环)

时间:2014-07-07 19:49:03

标签: python python-2.7 indentation

任何人都可以帮我解决以下问题,然后才能让我疯狂:)

`for row in reader:
if headers:
conn.execute('INSERT INTO COMPANY (Brand, Stock_Code, Description, Quantity,        Price_Ex_VAT) VALUES (?,?,?,?,?);', (row[0], row[1], row[2], row[3], row[4]))
y = y + 1
if x == 0:
        stdout.write("\rWorking \\")
#print("Working.", end = "")
   elif x == 1:
   stdout.write("\rWorking |")
   #print("Working..", end="")
   elif x == 2:
   stdout.write("\rWorking /")
   #print("Working..", end="")
   else:
   stdout.write("\rWorking -")
   x = -1
   #print("Working", end = "")
   stdout.flush()
   x = x +1
   else:
   headers = True 
   stdout.write("\n") # move the cursor to the next line
   stdout.write("Complete ")
   stdout.write(str(y))`

我现在已经搞乱这个约3个小时无济于事。谢谢你们

2 个答案:

答案 0 :(得分:2)

这应该有效

for row in reader:
    if headers:
        conn.execute('INSERT INTO COMPANY (Brand, Stock_Code, Description, Quantity, Price_Ex_VAT) VALUES (?,?,?,?,?);', (row[0],    row[1], row[2], row[3], row[4]))
        y = y + 1
        if x == 0:
            stdout.write("\rWorking \\")
            #print("Working.", end = "")
        elif x == 1:
            stdout.write("\rWorking |")
            #print("Working..", end="")
        elif x == 2:
            stdout.write("\rWorking /")
            #print("Working..", end="")
        else:
            stdout.write("\rWorking -")
            x = -1
            #print("Working", end = "")
        stdout.flush()
        x = x +1
    else:
        headers = True
        stdout.write("\n") # move the cursor to the next line
    stdout.write("Complete ")
    stdout.write(str(y))

对最后3个标准的凹痕不确定,但这应该有效。但是,如果您正在混合制表符和空格,那么您仍然会遇到问题。我不知道你正在使用什么编辑器,但你应该将标签扩展到空格。

答案 1 :(得分:1)

正如其他人所指出的那样,在Python中,缩进是有意义的。代码块应缩进。例如,if循环应该缩进,如下所示:

[伪]

if condition:
    performAction
elif otherCondition:
    performOtherAction
else:
    performDefaultAction

我试图重新格式化你的代码,因为我认为它应该是缩进的。评论你是否认为这应该是它应该是什么样子。

for row in reader:
    if headers:
        conn.execute('INSERT INTO COMPANY (Brand, Stock_Code, Description, Quantity, Price_Ex_VAT) VALUES (?,?,?,?,?);', (row[0], row[1], row[2], row[3], row[4]))
        y = y + 1
        if x == 0:
            stdout.write("\rWorking \\")
            #print("Working.", end = "")
       elif x == 1:
           stdout.write("\rWorking |")
           #print("Working..", end="")
       elif x == 2:
           stdout.write("\rWorking /")
           #print("Working..", end="")
       else:
           stdout.write("\rWorking -")
           x = -1
          #print("Working", end = "")
          stdout.flush()
       x = x +1
   else:
       headers = True 
       stdout.write("\n") # move the cursor to the next line
       stdout.write("Complete ")
   stdout.write(str(y)) #assuming that you are writing out the value of y regardless of value of headers