Home > Blockchain >  Sorting variables in Python and using the list in if statements?
Sorting variables in Python and using the list in if statements?

Time:08-11

I basically have 6 sensors, and I have 6 LED's corresponding to each sensor. I want the 3 sensors with the lowest value outputs to have their LED's turn on, and the other 3 to have their LED's off. This is what I've tried so far:

SortedSensors = sorted([sensor1, sensor2, sensor3, sensor4, sensor5, sensor6])

if sensor1 <= SortedSensors[2] #if it is in the lowest 3 outputs
     LED1 = 1 #turns it on
if sensor1 > SortedSensors[2] #if it is in the highest 3 outputs
     LED1 = 0 #turns it off

and then I repeat that if statement format for all 6 sensors. However, I was getting syntax errors. How do I approach this? Is this an easy fix, or do I need some sorting algorithm? I just need to have LEDs 1-6 equal 1 or 0. My code controlling the LED's works fine.

Here's my error: SyntaxError: invalid syntax (with an arrow pointing at the final bracket on line 3)

CodePudding user response:

SortedSensors = sorted([sensor1, sensor2, sensor3, sensor4, sensor5, sensor6])

Sensor2LED={
            sensor1 : LED1,
            sensor2 : LED2,
            sensor3 : LED3,
            sensor4 : LED4,
            sensor5 : LED5,
            sensor6 : LED6
    }

for sensor in SortedSensors[:3]:
    Sensor2LED[sensor]=1 #turn on low values

for sensor in SortedSensors[3:]:
    Sensor2LED[sensor]=0 #turn of high values

does this work for you?

CodePudding user response:

The syntax error was because I didn't have a colon. I'm new to python. Thanks guys!!

  • Related