<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>
<Below this line, add a link to the EXACT exercise that you are stuck at.>
18. To Your Battle Stations
<In what way does your code behave incorrectly? Include ALL error messages.>
When the battle stations lesson is over it is still possible to get error messages when running the program. If you put an invalid input the program crashes. Example, if you input the letter w instead of a number this error pops up:
Traceback (most recent call last):
File "python", line 32, in <module>
ValueError: invalid literal for int() with base 10: 'w'
<What do you expect to happen instead?>
So to stop this from happening I used two separate while loops (code below) for each coordinate input. This ensured a valid input had to be entered, but it seems complicated and clunky. Is there an easier way to solve for invalid inputs crashing the code?
```pythonfrom 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!”
print_board(board)
def protection(input1):
if input1.isdigit():
input1 = int(input1)
else:
print “that’s not a number”
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):
while True:
try:
print “For Row:”
guess_row = int(raw_input(“Enter Coordinate”))
except ValueError:
print “Enter a number!”
continue
else:
break
while True:
try:
print "For Col:"
guess_col = int(raw_input("Enter Coordinate"))
except ValueError:
print "Enter a number!"
continue
else:
break
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
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."
print "Turn", turn + 1
if turn == 3:
print "Game Over"
print ("Ship location:", ship_row, ship_col)
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
print "Turn", turn + 1
if turn == 3:
print "Game Over"
print ("Ship location:", ship_row, ship_col)
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "Turn", turn + 1
if turn == 3:
print "Game Over"
print ("Ship location:", ship_row, ship_col)
print_board(board)
<do not remove the three backticks above>