14/19 test run: what about letters?


#1

So during the testing and debugging I had the thought? what if someone entered a letter instead of a number? what code would you use to add an appropriate response? maybe this is covered in later lessons?


#2

It is not really covered in the lesson but that is the nice thing, you want to improve what you built.

Here is a link to my thread with my Full Battleship Game, check it out to see what you can do.

Here is some example code for you, use it if you would like. If you have any questions on it's operation ask.

ENTER INT, HANDLE NON-INT ENTRIES:

def int_entry(valid=False):
    """
    This function is used to get an int() from the user. 
    Convert raw_input() to input() for python 3.*
    :param valid: This is for flow control only
    :return: It will only return if the input == type(int)
    """
    # This while loop is used to continue even when an type(int) is not entered
    while not valid:
        # Try does exactly what it says on the tin
        try:
            # We assign the variable the input from the user
            # After the input function is run we attempt to
            # Convert it to an type(int)
            # If it fails the try will catch it as an Exception
            answer = int(raw_input("Enter a number"))
            # If the previous line passes it will set 
            # valid to True Breaking the while loop
            valid = True
            # Returns our answer
            return answer
        # This will catch any ValueError and preform a print out
        except ValueError:
            print("You did not enter and int type")

#3

I'm still pretty new to this, and python is my first coding language, so after the fact that you made the function "int_entry" (maybe haha) and the fact that "while" is some sort of loop, I dont really understand much of the code.
so "valid" starts as false, and while it is false, "try" (again new one haha) "ans" is the user input, and if it is a number then valid becomes true, if not return the error message (also new to me haha :) ) "you did not enter and int type"?


#4

@firecoder14

I tried to make it as human readable as possible. I like to code this way because a year from now I can look at it and discern what it does very quickly. That is a habit I support and encourage.

You have the gist of it as well, not much really going on in this function other than flow control. That is the meat of programming, you have to determine where you want the program to flow for it to succeed.

I will add some comments to my function for posterity's sake, so take a glance at it when you can.


#5

awesome, thanks a ton :smile: I think I understand it better now.
(sorry for the late response)