dimanche 22 mars 2015

How to validate input by the user until they enter the right format AND then how do I get out of the boolean loop? (Python 3.4)

So I am trying to get a specific format. I need the user to only enter from letters A to J and between the numbers 1-10. I also need the user to enter a space in the middle. I need to keep asking the user until they input something like "A 4" or "J 10". I've managed to keep asking for all types of things the user might enter, but I have also blocked the format I want and I really don't know how to go about it since I've been trying for a while now.


My while loop attempts to rule out all sorts of invalid input such as "4 D", "d", 4, "Y 9".


But I want the while loop to stop once user inputs something like "A 1" or "G 7".



alphabet = ['A', 'B', 'C' ,'D' ,'E', 'F', 'G', 'H', 'I', 'J']
numbers = ['1','2','3','4','5','6','7','8','9','10']

enterCoordinate = input('Enter coordinates x y (x in [A..J] and y in [1..10]) or s for ship status: ')
enterCoordinateL = enterCoordinate.lower()
coordinates = enterCoordinate.split()


while (len(enterCoordinate) <= 2) or (len(enterCoordinate) >= 4) or
(enterCoordinate[1] != ' ') or (enterCoordinate[0] not in alphabet) or
(coordinates[1] not in numbers):

enterCoordinate = input('Enter coordinates x y (x in [A..J] and y in
[1..10]) or s for ship status: ')

if (enterCoordinate[0] in alphabet) and (enterCoordinate[1] == ' ') and
(coordinates[1] in numbers) and len(enterCoordinate) == 3:
ty = input('The format is right now. ')

Aucun commentaire:

Enregistrer un commentaire