# Battleship! If no guess is entered crash

#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)
#print ship_row
#print ship_col
print "You have 4 turns to get it right"

# Everything from here on should be in your for loop
for turn in range(4):
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 sank my battleship!"
break
else:
if guess_row not in range(5) or \
guess_col not in range(5):
print "Oops, that's not even in the ocean."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print_board(board)
print "Turn",turn + 1
if turn == 3:
print "Game Over"
``````

if the player(me) hits enter before typing a number it crashes:

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
You have 4 turns to get it right
Guess Row: 4
Guess Col: 4
You missed my battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O X
Turn 1
Guess Row:
Traceback (most recent call last):
File “python”, line 28, in
ValueError: invalid literal for int() with base 10: ‘’

then you are unable to play on.

Do I just need to change something in:

if guess_row not in range(5) or
guess_col not in range(5):
print “Oops, that’s not even in the ocean.”

Or add a whole other line with a different print?

#2

if the user doesn’t enter anything, we get an empty string (`""`)

see what happens when you try to convert an empty string to integer:

``````int("")
``````

error, the moment `int()` gets a value it can’t convert to integer, it crashes

now, you could first prompt the user for input, then check if input is not empty (`if guess_row != ""`), but then when the user enters a list, you have the sam problem, so ideally you would do:

``````while True:
try:
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
break
except ValueError:
print "invalid guess, try again"
``````

this will catch the error

`try/except` allows us to handle errors, which is nice

adding a simple infinity loop will keep the user prompting till they enter something valid

#3

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