This error message bugs me


from random import randint

board = []

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

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

print "Let's play Battleship!"

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)

for turn in range(4):
    print "Turn", turn + 1
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "X"):
            print "You guessed that one already."
            print "You missed my battleship!"
            board[guess_row][guess_col] = "X"
    if turn == 3: 
        print "Game Over"

ok so i finished this battle ship lesson but theres something left out that bugs me, if i hit enter without entering anything or even just entering something that isnt an integer i get an error message, does anyone know what i would have to add to my code so that it would give me this error message.
im thinking an if statement but i wouldn't know what to write.
ty for any help


you could prompt the user for input with raw_input, but without converting to integer. Then check if the input is blank (check if input equals an empty string)

Catching other inputs becomes a bit more tricky, ideally you would use try/except, but this hasn't been covered


ahh yea hadent thought about removing the int bit on the raw_input, but then that leads me to another question, if say someone guesses a coordinate that "isnt even in the ocean" or if someone leaves a guess blank and is prompted to guess again would there be a way of writing it so that they dont lose that turn?


lets say they leave the guess blank, you can simply use a while infinity loop:

while True:
    # prompt the user

check if input is blank and prompt again, else break the loop

the second is a bit trickier, for loops make a fixed number of iterations. You could swap the for loop for a while loop, and then only increase the variable you use for the while loop when you see fit?


■■■■ i just love the way there are are so many different ways of doing one thing! ty for the help


which is both a blessing and a curse

if you want to catch everything, use try/except:

    # prompt the user 
except ValueError:
    print "inform the user they entered something invalid"
   # use else to break the loop when you use an infinity while loop to keep prompting

try/except allows us to catch errors


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