Search code examples
pythonwhile-loopcontrol-flow

Why two while loops one after the other (not inside the other) in Python don't work?


I wrote the code below and I was expecting that, when the first loop ends and doesn't return False, the flow would follow to the second while loop. However, the flow skips the second while loop and simply returns True. Why is that? How can I fix this problem, making the flow after the first while loop go to the second while loop?

square = [[1,2,3,4],[4,3,1,4],[3,1,2,4],[2,4,4,3]]
# this is an auxiliary function
def getSum(lis):
sum = 0
for e in lis:        
    sum = sum + e
return sum

# here is where the problem is
def check_game(square):
standardSum = getSum(range(1, len(square)+1))    

while square: #this is the first while loop
    row = square.pop()
    print row, 'row', 'sum of row=', getSum(row)
    if standardSum != getSum(row):
        return False
m = 0
while m < len(square): # the second while loop, which the flow skips 
    n = 0
    col = []
    while n < len(square):
        col.append(square[n][m])
        n = n + 1
    print col, 'column'
    if standardSum != getSum(col):
        print standardSum, ' and sum of col =', getSum(col)
        return False            
    m = m + 1
return True 

Solution

  • The first loop only terminates when there are no more items left in square. After the first loop, len(square) will be 0, so the entry condition for the second loop m < len(square) will be False.