neumear
neumear

Reputation: 121

flask - If-else only outputs 'if' condition

I have this program for PM levels detection and to output a message describing the level condition:

def pm25warnings():
    pm25 = getLastData()
    #if pm25 <= "50" :
    if pm25 <= 50 : #edited
        message = "PM 2.5 level is normal"
    else:
        message = "PM 2.5 level is high"
    return message

def pm10warnings():
    pm10 = getLastData()
    #if pm10 <="50":
    if pm10 <= 50: #edited
        message2 = "PM 10 level is normal"
    else:
        message2 = "PM 10 level is high"
    return message2

@app.route

    @app.route("/")
def index():
    time, temp, co, pm25, pm10 = getLastData()
    message = pm25warnings()
    message2 = pm10warnings()
    templateData = {
        'time'  : time,
        'temp'  : temp,
        'co'    : co,
        'pm25'  : pm25,
        'pm10'  : pm10,
        'message' : message,
        'message2' : message2,
        'numSamples'    : numSamples,
    }
    return render_template('index2.html', **templateData)

Might be useful to see:


    def getLastData():
    try:
        lock.acquire(True)
        for row in curs.execute("SELECT * FROM sensors ORDER BY timestamp DESC LIMIT 1"):
            time = str(row[0])
            temp = row[1]
            co = row[2]
            pm25 = row[3]
            pm10 = row[4]
        return time, temp, co, pm25, pm10
    conn.close()
    finally:
        lock.release()

I made a script to make random big numbers to trigger a high value level. But the wrong statement is shown in the html page:

html page showing wrong statement

... or perhaps is there other ways for me to implement this?

How can this be? Thanks in advance!

EDIT: I have edited the program thanks to the answers below but the page still shows the wrong statement:

enter image description here

EDIT 2: pm25 and pm10 is of TEXT datatype in the database (SQLite3). This problem might be a bit silly, given that my datatype is TEXT and not NUMERICAL, then, I couldn't do an e.g if pm25 < 100 because pm25 is 'TEXT`

Upvotes: 0

Views: 909

Answers (1)

Nick Reed
Nick Reed

Reputation: 5059

The statement if pm25 <= "50" is comparing pm25 to the literal string "50", not the number 50. If pm25 is a number, you need to remove the quotes.

    if pm25 <= 50 :
        message = "PM 2.5 level is normal"
    else:
        message = "PM 2.5 level is high"

Demo

After reading the comments posted on this answer, the data is being passed in as type string, with an example being "9.8\n". I forget if python lets you compare numberals in strings - better to avoid the headache and turn it into a number. Cast pm25 to float before comparing, as so:

    if float(pm25) <= 50 : #edited
        message = "PM 2.5 level is normal"
    else:
        message = "PM 2.5 level is high"

Upvotes: 2

Related Questions