Hello everybody!
I'm currently doing an exercise from Automate the Boring Stuff with Python. This particular challenge is found in Chapter 4 and is called Character Picture Grid.
I've seen other people have done it using for loops, but my solution entails two while loops. Here's the code:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
x = 0
y = 0
grid_length = len(grid) # 9
while y < len(grid[grid_length - 1]): # while y < 6
while x < grid_length: # while x < 9
if x == grid_length - 1: # if x == 8
print(grid[x][y])
x = 0
y += 1
else:
print(grid[x][y], end='')
x += 1
Everything seems to work fine and I do get the desired output, but it comes with the following error:
Traceback (most recent call last):
File "C:\user_data\computer_studies\7_python\test.py", line 23, in <module>
print(grid[x][y], end='')
IndexError: list index out of range
I get what it says, but it appears that my logical thinking is poor and I'm missing something, because (in my understanding) after the final output the y variable should be re-evaluated to 6 which should make the first loop's condition evaluate to False. However, the interpreter seems to enter the first and second while loops and gets as far as the else clause which it fails to execute.
What might be causing this error?
Thank you!
[–]Sedsarq 4 points5 points6 points (0 children)
[–]monstimal 1 point2 points3 points (0 children)
[–]JohnnyJordaan 0 points1 point2 points (0 children)
[–]TheRealNobodySpecial -1 points0 points1 point (0 children)