What when someone puts in a letter or nothing?


#1

Let’s say a player doesn’t add any input. What kind of if argument do I have to add in order to print out a string like “You need to put in a number!”.
I tried to create an if argument:

<<<if board[guess_row][guess_col] == []:>>>
<<< print “You need to put in a number!”. >>>

but that didn’t work. I can’t remember how i can say: “If the input is other than a number between 0 and 4 (so if it is a letter or nothing), do this.”

thanks


#2

There is no error checking for those inputs in the program but there is one line that will raise an exception if a non-number is entered…

guess_row = int(raw_input("Enter a Row: "))

#3

I put it under:
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))

but that gives me an error?!


#4

What error? Which exercise are you on? Please post a link to the lesson.


#5

Hi @sebilation,

You may have encountered a ValueError. While you are deciding how to handle this, see the example code in the official Python documentation at 8.3. Handling Exceptions. Since you are using Python 2, you will still need to use raw_input instead of input, which is what would be used in Python 3.

Also, please always post a link to the pertinent lesson when you ask for help in the Codecademy discussion forums, as @mtf has requested.


#6

ok sure, sorry about that. I am in battleship, I just finished the code, but I figured that when not entering any value or a letter, it gives me an error:

The same happens, when I add the code you mentioned:


#7

The error you are seeing is the exception that is raised when a non-number is passed into the int() function. This is what I was referring to in the earlier reply.

try:
    guess_row = int(raw_input("Guess Row: "))
    guess_col = int(raw_input("Guess Col: "))
except ValueError:
    print "Enter a number from 0 to 4."
    break

#8

When I try that, it gives me:

except ValueError:
^
SyntaxError: invalid syntax


#9

The error indicator points to the where it stopped parsing, which means the error is before that point. Check your typing.

https://docs.python.org/2/tutorial/errors.html


#10

alright! Thank a lot


#11

I figured it: i forgot the “try:” before the guess_row… etc.

Thanks a lot for the help!! really appreciated!


#12

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