Vedad - 14 days ago 5
Python Question

# Infinite loop iterating a column of an array in Python

I have an issue iterating through an array of 6x8 elements. Somehow I get an infinite loop. But I don't see any logical mistakes.

``````array=[[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "],[" "," "," "," "," "," "," "," "]]

i=1
j=1
while i<=6:
if "O" in array[i][j]:
i = i + 1
if i > 4:
print("Game over")
``````

I can actually put some input into the array. The Array represents something like a chess field. I want to count in every turn how often an
`"O"`
is occurred in the column 1. If it occurs more then 3 times, it should print
`"Game over"`
. But the loop becomes infinite.

The loop is infinite because the `i` variable is not incremented, if `"O" in array[i][j]` condition is `False`.

Besides, there is a better way to iterate arrays in Python:

``````def check_column_cells(array, column):
counter = 0

for row in array:
if row[column] == "O":
counter += 1
if (counter > 3):
print("Game over")
return counter

return counter

# Check the 2nd column (the indices start from 0)
print(check_column_cells(array, 1))
``````

If you still would like to use indices, apply the increment operations:

``````def check_column_cells(array, column):
counter = 0

r = 0
while r < len(array):
if array[r][column] == "O":
counter += 1
if (counter > 3):
print("Game over")
return counter
r += 1

return counter

# Check the 2nd column (the indices start from 0)
print(check_column_cells(array, 1))
``````

Note, I have skipped security checks for clarity's sake. In the functions above, you should check if the column index is in the available range, for instance.