Stuck in this section


#1

i am also stuck in this section: the below code runs fine but i am getting an error while putting the values of guess_row and guess_col on console, i tried different values like 0,1,2,3,3,5 but nothing works.could you please help:

code:
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)
print ship_row
print ship_col

guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess 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!”
[guess_row][guess_col] = "X"
print_board(board)

Error :

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
2
4
Guess Row: 1
Guess Col: 1
You missed my battleship!
Traceback (most recent call last):
File “python”, line 34, in
IndexError: list assignment index out of range


Danger, Will Robinson!
#2

your code all looks correct…EXCEPT this line
you wrote:
[guess_row][guess_col]=‘X’

However, you didn’t specify the list name. You specified the row and column but row and column of what? You need to specify row and column for the list called “board” that was created.
So, you need:
board[guess_row][guess_col] =‘X’


#3

It worked… Thanks a lot.:grinning:


#4

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