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


#1

Question

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

Answer

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
#2

still in the battleship course I have a question :
Why is differently written the return command in len(board… ???

first is len(board)-1 and then len(board[0] - 1) … shouldn t it be the same ?
more exactly : board vs board[0]

def random_row(board):
return randint(0, len(board) - 1)

def random_col(board):
return randint(0, len(board[0]) - 1)


#3

as long as the board is a square its the same, however what if you have a rectangle board? 5 by 8 for example