当找到 2 个连续的空单元格时,中断 python 循环

Break python loop when it finds 2 consecutive empty cells

我想使用循环计算 Excel table 中存在的行数和列数,循环应该在遇到 2 个(或更多)连续空单元格时停止 运行 .

row_count=0
col_count=0

for a in range(1,temp.max_row+1):
   if temp.cell(row=a,column=2).value!=None:
       row_count= row_count+1
   else:
       break
for b in range(2,temp.max_column+1):
   if temp.cell(row=8,column=b).value!=None:
       col_count=col_count+1
   else:
       break
print(row_count)
print(col_count)

但是,我使用的方法无法得到正确的结果。

您需要在每次迭代中检查两个相邻的单元格:

for a in range(1,temp.max_row+1):
   # Check if the cell is not empty
   if temp.cell(row=a, column=2).value is not None: 
       row_count = row_count + 1

   # Else the cell is empty, check if the next one is also empty
   elif temp.cell(row=a + 1, column=2).value is None: 
       break

for b in range(2,temp.max_column+1):
   if temp.cell(row=8, column=b).value is not None:
       col_count = col_count + 1
   elif temp.cell(row=8, column=b + 1).value is None:
       break

感谢您回答我的问题。我做了一些更改,下面的代码似乎最适合我的数据。-(代码的目的是测量 excel sheet 中 table 的维度( sheet 包含多个这样的 tables)。所以如果它遇到,比如说,2 个连续的空单元格,它必须停止计数,然后才能到达另一个 table。)

# A) For 2 consecutive empty cells- 

#for rows: 
for a in range(4, temp.max_row+1):
    if (temp.cell(row=a, column=2).value==None and temp.cell(row=a+1, column=2).value==None): #check if current cell & the following cell is not empty. if empty, it stops counting & exits the loop.
        break
    else:
        row_count=row_count+1


#for columns: 
for b in range(2,temp.max_column+1):
    if (temp.cell(row=20, column=b).value==None and temp.cell(row=20,column=b+1).value==None):
        break
    else:
        col_count = col_count+1