Search code examples
pythonconways-game-of-lifeindexoutofrangeexception

How to 'ignore' an index out of range error in Python


My teacher set me the task to make a Python version of "The Game of Life", So after I got most of the code working. I got stuck on what I suspect would be a rather common problem: The corners and edges don't have 8 neighbors. So using the following code would give me an index out of range exception:

neighbors = (a[x-1][y-1]+a[x-1][y]+a[x-1][y+1]+a[x][y-1]+a[x][y+1]
             +a[x+1][y-1]+a[x+1][y]+a[x+1][y+1])

So instead of using a lot of if statements, I wanted to catch the indexes that are out of range and pass the value 0 instead. How would I attempt to do that?


Solution

  • I would write a helper function that you could call that would either return a value or zero (pseudocode):

    def getValue(x, y)
       if x < 0 or y < 0 or x > xbound or y > ybound:
           return 0
       return a[x][y]
    

    Then you can call getValue a bunch of times with different parameters