0

Basically, I'm asking for an input, which is going to be split(',') however, if the person doesn't input it properly, for example they accidentally input just 5, or don't include a comma at all, it comes up with an error that something is undefined.

Does anyone have any idea of how to check that the input is in the right sort of format?

Edit: Here's the code in question...it's to do with coordinates

def EnterCoords():
    coordinates = input("Enter coordinates in the following format x,y").split(',')
    x, y = Coordinates[0], Coordinates[1]

I then use the x and y values in a calculation elsewhere, which brings up the error IndexError: list index out of range So, if the user enters them wrong, is there a way of calling the function again, for them to try again

brisbass
  • 199
  • 1
  • 2
  • 8
  • show the actual error – Padraic Cunningham Jan 25 '15 at 19:47
  • 3
    Welcome to StackOverflow. You'll be much more likely to get a useful answer if you can include some code and the error you're seeing. – acrosman Jan 25 '15 at 19:48
  • 3
    I'm honestly sick of SO shutting down perfectly good questions. To OP: catch the `ValueError`. It's hard to know precisely if the text is formatted the way you want it until `split()` actually runs. – James Taylor Jan 25 '15 at 19:52
  • 2
    are you using input or raw_input? – Padraic Cunningham Jan 25 '15 at 19:52
  • The question appears to be about defensive programming in general (focused a bit on the problem of input validation / sanitization). I don't think it is about a single, specific error. It actually seems like a reasonable question to me as-is. Well answered by a simple try-except example, and a discussion of why defensive programming is bad in a dynamically typed language (and in general too). – ely Jan 25 '15 at 19:53
  • 1
    Instead of checking for a specific format, try searching for a specific values: `data = raw_input('Enter a few values: ') # let's say 1, 3, 4.5, 5, nums = [] for entry in re.findall('[0-9.]+', data): nums.append(float(entry)) print nums # now just numbers regardless of commas` – Malik Brahimi Jan 25 '15 at 19:56

2 Answers2

2

Given your updated question, then the best way is to use a try/except.

def enter_coords():
    while True:
        try:
            # Use `raw_input` for Python 2.x
            x, y = input('Enter coordinates ...: ').split(',')
            return int(x), int(y) # maybe use `float` here?
        except ValueError as e:
            pass

Keep looping until a successful return. By using x, y = - you're requesting that only two values should be unpacked (less or more will raise a ValueError), if that succeeds, then you try to return the int equivalent of those values, again, if they're not suitables ints, then you get a ValueError... you then ignore that error and the loop repeats until a successful return executes.

More general approaches and the principles of using this approach are detailed in the excellent: Asking the user for input until they give a valid response

Community
  • 1
  • 1
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
-1

Edit: Just realized you're not looking for alpha only string.


To check for commas use any of the following: There are multiple ways of solving this problem:

Using in operator

Check for a comma in the string using the in operator:

if "," in str:
 <code on true condition>

Example:

In [8]: if "," in "Hello World!":
   ...:     print "Contains Comma"
   ...:     

In [9]: if "," in "Hello,World":
   ...:     print "Contains Comma"
   ...:     
Contains Comma

-OR-

Exception Handling

You could use try ... except block to check for error when ',' is not present in string as suggested by James Taylor. See documentation for handling exceptions: https://docs.python.org/2/tutorial/errors.html#handling-exceptions

-OR-

RegEx

As suggested by Malik Brahimi in the comments - "Instead of checking for a specific format, try searching for a specific values":

data = raw_input('Enter a few values: ') # let's say 1, 3, 4.5, 5,
nums = []

for entry in re.findall('[0-9.]+', data):
    nums.append(float(entry))

print nums # now just numbers regardless of commas
Manav Kataria
  • 5,060
  • 4
  • 24
  • 26
  • I believe regex is another valid way of solving the OP's problem. Your edit is worthy to be an independent answer. Kindly add one to augment the discussion. – Manav Kataria Jan 25 '15 at 20:06
  • I wasn't trying to be rude, the topic's been put on hold, and you seem to be accumulating downvotes. I thought my answer might be of use to you. – Malik Brahimi Jan 25 '15 at 20:08
  • Appreciate the clarification Malik, I will incorporate your answer. Secondly, that downvote was well deserved - due to misunderstanding of the OP's question which I've corrected since. – Manav Kataria Jan 25 '15 at 20:11
  • I didn't downvote you, don't be too hard on yourself. – Malik Brahimi Jan 25 '15 at 20:13