Why do I get a list index out of range error?



Why do I get a list index out of range error?


It’s crucial that you get the order of your conditions right, otherwise you might try using invalid user input before checking for it to be invalid. The order, in pseudo code, should be as follows:

if guess is correct:
  print “Congrats! You sunk my ship.”
else, not correct:
  if guess is invalid:
    print “Not in the ocean”
  elif already guessed:
    print “Already guessed!”
  else, just missed:
    print “Missed!”
    update element in board to be “X”
  print the board

Notice the order in which we check things:

  1. If the input is correct, it is valid and we’re done.
  2. OTHERWISE (else), we check everything else. The very first thing we check inside the else is for the input to be invalid (not in the range() of our board list.
  3. The last things we do are use the user-input coordinates to check if they’ve already guessed and to print the board. If we try to print the board or use those invalid inputs in any way, it will cause an error.

FAQ: Learn Python - Battleship - Test Run