Search code examples
pythonpython-3.xfor-loopwhile-loopuser-input

Python: obliviate user input that has become obsolete


I created my version of the game all beginners at Python play: Battleship. The user must define two coordinates, X and Y.

I have made a validation, which rejects any input that is not an integer. If input is integer, the code continues to execute. At the end, however, I need to hardcode the current user input in a string, or else the code will not enter the while loop and re-prompt the user for another set of coordinates when the next turn starts.

This in fact works just fine, yet I feel like this is not the cleanest way to handle this.

Can anyone suggest a better way to do this?

# ships are positioned, user must sink them

for turn in range(num_of_turns):
    print("Turn", turn + 1)
    while type(guess_col) is not int:
        try:
            guess_col = input("Enter coordinate X: ")
            guess_col = int(guess_col)
        except ValueError:
            print("Enter coordinate X again")
            continue
    while type(guess_row) is not int:
        try:
            guess_row = input("Enter coordinate Y: ")
            guess_row = int(guess_row)
        except ValueError:
            print("Enter coordinate Y again")
            continue

        # do stuff (sink ships, miss ships, etc...)

    guess_col = str(guess_col)
    guess_row = str(guess_row)

Solution

  • One solution is to set guess_col to something that isn't an int just before the while loop:

    guess_col = ''
    while ...:
    

    I suggest that you learn about functions. These are a very important tool that helps you to organize code into small, coherent, reusable pieces. For example, you can write a function get_int() which does the validation and returns the value when the user types in a number. You can then reuse this function to get the input without repeating code like you do in your current solution. You can do something like

    guess_col = get_int()
    guess_row = get_int()