Danger, Will Robinson!


#1

Hi,
This line: “X” = board[guess_row - 1][guess_col - 1], the error states that it can’t assign to literal. May I know why is this so?

Below is my 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!”
“X” = board[guess_row - 1][guess_col - 1]
print_board(board)Preformatted text


#2

If you do

"x"=5+5

you’ll get an error

SyntaxError: can't assign to literal

but if you do

no

x=5+5

no error

now consider what is x in both case?


#3

For the first line “x” is a string, while the other one is simply a variable?
I can see that a string cannot be the sum of two numbers

Is there a difference between

board[guess_row - 1][guess_col - 1] = “X”
“X” = board[guess_row - 1][guess_col - 1]


#4

Of course there is :slight_smile:

In the first line of code you are assigning "X" to board[guess_row - 1][guess_col - 1] that is valid.

But for the second one you are trying to assign board[guess_row - 1][guess_col - 1] to "X" that is invalid.

the object on the left-hand side of the = sign can’t be a literal.


#5

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