Simple Python IF statement does not seem to be working

前端 未结 1 712
臣服心动
臣服心动 2021-01-27 03:35

I\'m new in python and I\'m writing a simple script to work with Firebase but I\'m stuck on a simple if statement that seems not working as expected:

## check fo         


        
相关标签:
1条回答
  • 2021-01-27 04:07

    You are comparing strings with floating point numbers.

    minTemperature, maxTemperature, minHumidity and maxHumidity are all float objects because you converted them. But temperature and humidity are strings, because otherwise Python would have thrown an exception when you tried concatenating them with other strings.

    Compare float to float by converting either in the test:

    if float(humidity) > maxHumidity:
    

    etc. or by converting humidity and temperature to floats and converting them back to strings when inserting into Firebase.

    In Python 2, different types of objects are always consistently sorted, with numbers coming before other types. This means that < and > comparisons are true or false based on the sort order of the two operands, and since numbers in Python 2 are sorted first, any comparison with another type is done with the number considered smaller:

    >>> 3.14 < "1.1"
    True
    

    Python 3 does away with trying to make everything orderable; comparing a float to a string gives you a TypeError exception instead.

    0 讨论(0)
提交回复
热议问题