Adding a type checker to the guess_col and guess_row inputs


#1

Hey everyone,

While I was doing the battheship section, I noticed that a hole remained in the program even when using the expected code: if the player enters a non-integer value in the prompt (e.g. a letter), the thing crashes. So I thought it would be a nice extra exercise to expand the code to include a part that basically does this:

  • Take both inputs
  • If one of the two inputs isn't an integer, display a message (e.g. numbers only you twit" and rerun the prompt
  • Else, run the game as expected.

To do so, I wrote a check() function:

def check():
guess_row = (raw_input("Guess Row:"))
guess_col = (raw_input("Guess Col:"))
if type(guess_row) != int or type(guess_col) != int :
print "You fucked up brah"
check()
else:
guess_row = int(guess_row)
guess_col = int(guess_col)

But here comes trouble:

  • By definition, the int(raw_imput()) makes the input an integer, so the check will always go through.

  • Without the int(), any letter will be understood as an undefined variable and crash the game.

  • Idem with input() and any combination of it with the above functions I tried.

So, my second idea would be to check if a conversion of the input would give a valid integer: if yes, feed it to the guess_row/col variables; else, display the message and rerun the prompt. To do so, I tried quite a few combinations, like:

g = (raw_input("Guess Row:"))
if type(int(g)) == int:
g = int(g)

But none of them seem to work.

Would anyone know of a way to solve this problem? The idea would basically be to check if the input is/could be converted into an integer before feeding it to the variable/conveting it.

Cheers.


#2

I would probably created a function similar to this:

def guessRow(userInput):
if userInput.isdigit() == True:
Guess_Row = userInput
else:
print 'Please try again'
guessRow(raw_input("Guess Row: "))
guessRow(raw_input("Guess Row: "))