# Error for Empty Input

#1

When only one value out of the board, or when nothing is entered at all, it kills the program saying there is an error in the code. Is there something I could put in to stop this, and print a message to the effect of "Please pick a space actually on the board" (when they pick 8,3 for example), or "You didn't enter anything" (when they leave one or both inputs blank)?

``````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!"
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)

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

#correct
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations, you win. Did you want a cookie or something?"
break
#out of grid
else:
if (guess_row < 0 or guess_row > 5) or (guess_col < 0 or guess_col > 5):
print "Seriously? That's not even in the ocean!"
elif(board[guess_row][guess_col] == "X"):
print "Now you're wasting turns? You already guessed that!"
#missed
else:
print "Haha! You missed!! You'll never win at this rate!"
board[guess_row][guess_col] = "X"
if turn == 4:
print "You lost. That sucks. Better luck next time, loser :P"
print_board(board)``````

Yes, I know some of my code is changed. I changed how it shows misses (cause for example 2,4 would show up in the 3,5 spot). I also gave them 5 turns instead of 4, and made the npc messages sassier. But none of this has effected whether the code works as far as I can tell/test.

If you have a solution to the empty answers/single wrong answer, please let me know thanks!

#2

An if statement could do it. The logic you'd want is:

``````if both guesses aren't in the range of acceptable guesses:
Print message.
Go back to the start of the for loop.  - This will cost a turn.
Convert guess to int after passing``````

Now, if you don't want it to use a turn, use a while loop after getting the guesses. The logic would be:

``````While guess not in range of acceptable answers:
Print message.
Get raw input for guess again.
Convert to int after passing while loop``````

#3

catching empty input is easy. Just prompt the user (don't convert to integer), check if input is empty (compare with empty string), if not, convert to integer

however, if you also want to catch invalid input (like strings), the best approach is try/except, this allows you to catch errors:

``````try:
# get user input and try to convert to integer
except ValueError:
print "not a integer"``````

try/except is not covered in course, you can look in the official python docs for explanation

#4

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