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
2 Answers 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
6 Comments
while True there though :pfrom contextlib import suppress with suppress(Exception): which will ignore the exception, it replaces the try/except: passEdit: 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
ValueError. It's hard to know precisely if the text is formatted the way you want it untilsplit()actually runs.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