Test Run: Help Catching Input Errors


Battleship 14: Test Run

Hi, so I'm trying to get my code to loop back to the beginning if an invalid input is entered.

Unfortunately, the way I've written it, it does seem to loop during input, but doesn't appear to be saving the variable for use later.

I think there are some other bugs too with how it checks for the "X" in the grid, but I can't debug that right now with the input error, so if anyone happens to catch what I'm doing wrong there, I would really appreciate it.

Here's the error:

Traceback (most recent call last):
  File "python", line 55, in <module>
NameError: name 'guess_row' is not defined

Here's 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)


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)
def guess():
    invalid_row = True
    invalid_col = True
    while invalid_row == True:
        raw_guess_row = raw_input("Guess a row:")
        if raw_guess_row.isdigit():
            guess_row = int(raw_guess_row)
            if 1<= guess_row <= 5:
                invalid_row = False
                return guess_row
                print "Invalid input. Try a value between 1 and 5."
            print "Invalid input. Try a value between 1 and 5."
    while invalid_col == True:
        raw_guess_col = raw_input("Guess a column:")
        if raw_guess_col.isdigit():
            guess_col = int(raw_guess_col)
            if 1<= guess_col <=5:
                invalid_col = False
                return guess_col
                print "Invalid input. Try a value between 1 and 5."
            print "Invalid input. Try a value between 1 and 5."
    return guess_row
    return 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!"
elif board[guess_row][guess_col] != "O":
    print "You guessed that one already."
    print "Try again."
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print "Try again."


In your guess() function
initialize your guess_row and guess_col variables to a Value 10

If you use a return statement in a function
the Value is returned AND the function is immediately EXITED
any following statements will NOT be executed.....
if you use

    return guess_row
    return guess_col

the guess_col will never be returned.....
Possible solution,
create a result_list
and then return the list

return result_list


Ah! That makes sense. I'll give it a shot. Thanks for the response!