I have a function that in some cases might get as input something that is not suited for what the function is supposed to do. When this is the case, rather than stopping the program and returning an error, I would like the function to simply return something specific, like for example the string there is something wrong in the input
.
Let me show a specific example. This is a function that takes as input the string indicating a chess move and returns the actual move in the form of a list (initial square and final square).
def move_name_converter(name):
columns=list(string.ascii_lowercase)[:8]
columns.reverse()
move=[]
move.append([int(name[1])-1,columns.index(name[0])])
move.append([int(name[3])-1,columns.index(name[2])])
if len(name)==5:
move.append(name[4])
return move
if I give a proper input everything works fine:
print move_name_converter('a2a3')
will correctly return
[[1, 7], [2, 7]]
If instead I give a bad input:
print move_name_converter('whatever')
it returns a ValueError
.
Rather than returning an error (any kind of error), I would like the function to just print a string like this is not a valid input
.
I could solve the issue by carefully consider every possible way the input could be bad, but is there a way to generically make the function return a given output whenever there is an error?