Rafii1
Rafii1

Reputation: 29

How to end iter_rows loop when cell value is empty?

I am trying to iterate through cells and then stop the loop when I hit the first empty cell.

For this purpose I wrote the loop:

best_ten = []
for row in sheet.iter_rows(min_row=1, max_col=1, max_row=100):
    for cell in row:
        if cell.value:
            best_ten.append(cell.value)
        else:
            break

However, the empty cells just get skipped. I want the loop to end when the first empty cell is hit.

How can I achieve that?

Cheers

Upvotes: 0

Views: 1051

Answers (1)

Jonas Byström
Jonas Byström

Reputation: 26159

If you use a return statement within a function, you can break out of both for loops:

def find_best_ten():
    best_ten = []
    for row in sheet.iter_rows(min_row=1, max_col=1, max_row=100):
        for cell in row:
            if cell.value:
                best_ten.append(cell.value)
            else:
                return best_ten
    return best_ten

Upvotes: 1

Related Questions