I am writing some functions in python3 to work with some GPS data received by UART. Those data I have to cast them and leave them ready to later work with them.
However, I am faced with the question of how to do it, because at first I had tried to do it in the following way:
def gga_read(data_in):
tmp = data_in.replace("*", ",")
data_out = tmp.split(",")
if len(data_out[1]) == 0:
data_out[1] = 123456
print("Datos no válidos. Muestra valor genérico.")
else:
data_out[1] = float(data_out[1])
return data_out
To work, it works, but I do not know if it would be the best way to do it for each of the elements of the list that I have to work with (one should do more than one if else or try except). Anyway, I tried to do it in the following way:
def gga_read(data_in):
tmp = data_in.replace("*", ",")
data_out = tmp.split(",")
''' Cast de elementos del vector y mensajes de error '''
try:
data_out[1] = float(data_out[1])
except ValueError:
print("Datos hora UTC no válidos. Se aplicará un valor genérico de 123456")
data_out[1] = 123456
return data_out
So, the question is how to proceed so that the code is better. Well I do not know whether to do it with if else, exceptions or another better way. What do you suggest?