FAQ: Learn Python - Battleship - To Your Battle Stations!

Was there any solution to this?

Same answer? I can only help you, if you share your code


So I’ve been playing around with this code for a while now - a few things annoyed me which I think I have fixed! For example, in the version the tutorial asks you to make, you can’t input the number 5 for the row or column raw_input.

There are still 2 things that are bugging me however which I can’t seem to solve!

1: If you take too long to enter a raw_input, the following error appears

Traceback (most recent call last):
File “python”, line 27, in
ExecTimeoutException: Program took too long to terminate.

2: If your raw_input is nothing or anything other than a number, you get the following error:

Traceback (most recent call last):
File “python”, line 27, in
ValueError: invalid literal for int() with base 10: ‘’

Any help with these two issues would be much appreciated! I’ve tried using if guess_row.isalpha() but I haven’t been able to get that to work but perhaps I’m putting it in the wrong place!..

My code below.
Thanks for your help.

The first one you can’t do much about, you could perhaps handle the exception? Try catch hasn’t been taught?

we could do this:

except  ExecTimeoutException:
   print "Handle the exception"

try catch allows us to catch exceptions which occur.

We could do the same thing for the ValueError.

Or you could prompt for input, then check if the input is a digit before converting to integer. isalpha is not the right method, isalpha checks if all the characters are alphabetical (a-z), which is not what you want

Amazing, thank you! Will give these a try :slight_smile:

How could I alter my code so that an invalid guess (non integer, repeated guess, or out of range guess) would not increase the turn count? Originally I tried including “turn -= 1” in my “for turn in range(4)” loop, but obviously that doesn’t work (I’m assuming because turn isn’t a variable?)

I can see a workaround where at the point that an invalid guess is made, I immediately ask for another input, but that seems like it would lead down a wormhole of wordy code (what if they enter a second invalid guess?). What I’m looking for is a method of not necessarily breaking the for loop but stopping before reaching the end of the loop and restarting on the same turn (so essentially just backing up a few lines).

I’m sure there’s a good way to do this, but I’m totally new to python and just trying to anticipate ways to learn more from this exercise. Thanks for any help.

This would make the number of iterations unknown (given you can’t know how many invalid inputs the user is going to give)

then the while loop is a much better choice.