0

So, here is my code:

print "at which cell do you want to place your character? (x,y)"

coordinates = raw_input("> ")

while coordinates != "int,int":
    print "Please enter an x and y value separated by a comma."
    coordinates = raw_input("> ")

What I currently have obviously does not work, just typed it out to show what I want to do. Basically, if the user does not enter a number followed by a comma followed by another number I want to reprompt them until they do.

Edit: Fixed it. Here's what I ended up with.

coordinates = raw_input("> ")
while True:
    try:
        x, y = coordinates.strip('()').split(',')
    except ValueError:
        print "Please enter an x and y value separated by a comma."
        coordinates = raw_input("> ")
    else:
        break
Nikita Petrov
  • 51
  • 1
  • 1
  • 5
  • See [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658) – Martijn Pieters Apr 14 '15 at 23:01
  • You'll need to *split* your input string (`coordinates.split(',')`) and try and convert each element to an integer, using the techniques of the other answer. – Martijn Pieters Apr 14 '15 at 23:02
  • @MartijnPieters The split thing is not working for me because if they enter an invalid input it just crashes when attempting to split. I need to split only if I know for sure they entered a valid input. I understand how to ask a user again for input, I just dont know how to check correctly in this particular case. – Nikita Petrov Apr 14 '15 at 23:12
  • `raw_input` always returns a string; `coordinates.split(',')` won't crash. Python doesn't crash either; it throws an exception instead. See the other answer on how to handle exceptions instead of letting Python exit because you ignored the exception. – Martijn Pieters Apr 14 '15 at 23:14
  • `coordinates = coordinates.split(',')` is the first step. You can then check for the length (is it anything other than 2? That's invalid input. You can then check if each value can be converted to an integer with `int()`. Does that throw a `ValueError`? Then you have invalid input. Etc. – Martijn Pieters Apr 14 '15 at 23:15
  • Ended up figuring it out, edited my question to reflect that. Thank you for the help! I was combining splitting and stripping values out of the input which was causing the crash. – Nikita Petrov Apr 14 '15 at 23:32

0 Answers0