I'm making a 3 in a row game for practice using the concepts I have learned in class so far: while loops, booleans, and if-statements.
For some reason, my function doesn't seem to be returning False even though I give an argument in which it should. Instead I get a 'executing command, please wait for result' message, where nothing comes up after that. Initially I thought it was caught in an infinite loop somewhere, but I don't think it should as I gave limits to all my variables and added the +=1 at the end for all of the while loops.
Any help will be much appreciated!
Here is a snippet of my code below:
def is_winner(grid):
x = 0
y = 0
while x <=3:
x +=1
while y <= 4:
if grid[x][y] == grid[x + 1][y] ==grid[x + 2][y]:
y += 1
return True
while x <= 3:
x +=1
while y <= 3:
if grid[x][y] == grid[x + 1][y - 1] == grid[x + 2][y - 2]:
y +=1
return True
else:
return False
1 Answer 1
You only ever increment y if the if statements are True. If they never are, you entered into an infinite loop:
while x <=3:
while y <= 4:
x +=1
if grid[x][y] == grid[x + 1][y] ==grid[x + 2][y]]:
y += 1
Your inner while loop never completes, so your outer while loop is never tested.
Change this to:
while x <=3 and y <= 4:
x +=1
if grid[x][y] == grid[x + 1][y] ==grid[x + 2][y]]:
y += 1
3 Comments
grid list contains other lists, then using grid[x] refers to an index in the outer list, and the [y] part then applies to that returned value, also a list. If you get string index errors, then either grid is a string itself or it is a list where at least one of its values is a string.Explore related questions
See similar questions with these tags.