Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If none of the above python

Tags:

python

I have a series of checks I need to run on sensor data, the checks are all independent so they can't be formatted as elifs or elses, if any checks fail, I need to print this to the user. If none of the checks fail I want to tell the user the sensor is okay

(i is just an iterator going over all the sensors in the array)

if worst_stdev[i] > 5:
    print("Sensor bad, STDEV VALUE: {}".format(worst_stdev[i]))
if worst_invalid[i] > 2:
    print("Sensor bad, INVALID VALUE: {}".format(worst_invalid[i]))
if worst_err[i] > 1:
    print("Sensor bad, ERROR VALUE: {}".format(worst_bit_err[i]))
if not (worst_stdev[i] > 5 or worst_invalid[i] > 2 or worst_err[i] > 1):
    print("Sensor OK")

The last if statement bugs me the most, it feels redundant (and possibly slower?) to check again for all the things I've already checked. Is there good way to make this more elegant?

like image 385
Indigo Avatar asked Dec 06 '22 13:12

Indigo


1 Answers

I would keep a flag variable that keeps track of errors. For example:

was_error = False
if worst_stdev[i] > 5:
    print("Sensor bad, STDEV VALUE: {}".format(worst_stdev[i]))
    was_error = True
if worst_invalid[i] > 2:
    print("Sensor bad, INVALID VALUE: {}".format(worst_invalid[i]))
    was_error = True
if worst_err[i] > 1:
    print("Sensor bad, ERROR VALUE: {}".format(worst_bit_err[i]))
    was_error = True
if not was_error:
    print("Sensor OK")

Alternatively you could have several different error variables so that you can tell which error occurred. If you don't care which error was thrown, but do want to know how many of them there were, you can increment the error variable each time. This has the upshot of still working with the syntax if not was_error:

like image 139
bendl Avatar answered Dec 25 '22 19:12

bendl