Not Again.!


#1



from random import randint

board = []

for x in range(0, 5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

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

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

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

# Write your code below!
if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)
if guess_row not in range(5) or  guess_col not in range(5):
    print "Oops, that's not even in the ocean."
else :
    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sank my battleship!"
    elif board[guess_row][guess_col]:
        print "You guesses that one already."
    else:
        print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)

https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/1/4?curriculum_id=4f89dab3d788890003000096#

Traceback (most recent call last):
File "python", line 33, in
IndexError: list index out of range

when i enter as raw input row = 6, col = 6 it shows this error. If i enter row = 2 and col = 3 it don't show this error..


Replace this line with your code.


#2

Your board is 5x5 if you write col 6 and row 6 this will appear,

Because it's not on the board.

What you should start looking into is why your if statement did not execute the string

when you typed 6 and 6 on a 5x5 board.


#3

make sense? your list is 5 long, so the indexes are 0,1,2,3,4. If you enter something higher, the index doesn't exist (hence the error)

Enter something valid for now, you will add some code to catch numbers which are not in range later


#4

yes i am looking for "Oops, that's not in the ocean" but its not printing instead it shows that error


#5

Where i am wrong in my code..pls correct.


#6

to check if it is in the ocean should (obviously) come before you enter coordinates


#7

Here,

remove this bit try as much to never repeat yourself ,

The main problem is'actually control flow if you wrote your code in the proper order you would encounter minimal errors. But right now your conditional statements are all abit off. I would suggest rewriting the code in the proper rder first. :grin:


#8

2 posts were split to a new topic: Not again


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.