What is wrong with this code?


#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:
    if guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col] == "X":
        print "You guessed that one already."
else:
        print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)

Hello, I can't seem to understand what is wrong with my code. It keeps throwing up an error saying the elif statement has an invalid syntax. Help will be appreciated.


#2

this bit is has a few problems:

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

you can have an if, followed by 0, 1, 2 or more elif, and if you want, you can have a else after it. either way, you have a if, then a else, and then if else (you can't, else should always be last), followed by another else, you can only have one else, else covers everything else (all remaining options, so you can't have two), take a close look at your if, elif and else and indent

Oh, hold on, i think i understand, this:

    if guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
elif board[guess_row][guess_col] == "X":
        print "You guessed that one already."
else:
        print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)

should all be part of your else:

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    # the if, else if and else from above should be here

see comment, your indents aren't properly


#3

Thanks a ton! Your suggestions worked like a charm :smiley:


#4

It is cool how we can work it the above way. Or we can follow the instructions from the beginning up to the if - else stage, then insert every instruction after, leaving the else at the end.

if
elif
elif
else

#5

This was pretty helpful too! Thank You!