简单的python如果语句不起作用

时间:2016-05-21 14:19:58

标签: python if-statement firebase

我是python中的新手,我正在编写一个简单的脚本来使用Firebase,但我已经找到了一个似乎没有按预期工作的简单if语句:

## check for max values
if humidity > maxHumidity:
    firebase.put("/Controls/Sensors", "/Humidity/max_inside", ""+humidity+"%")
    print("Updating Humidity max_inside")

if temperature > maxTemperature:
    firebase.put("/Controls/Sensors", "/Temperature/max_inside", ""+temperature+"C")
    print("Updating Temperature max_inside")

## check for min values
if humidity < minHumidity:
    firebase.put("/Controls/Sensors", "/Humidity/min_inside", ""+humidity+"%")
    print("Updating Humidity min_inside")

if temperature < minTemperature:
    firebase.put("/Controls/Sensors", "/Temperature/min_inside", ""+temperature+"C")
    print("Updating Temperature min_inside")

问题是前两个if语句按预期工作,最后两个不是..如果湿度&lt; minHumidity,没有任何反应。 我使用的价值是双倍的,如70.50 ..

修改

##retrive max & min humidity (remove the %)
maxHumidity = firebase.get("/Controls/Sensors/Humidity/max_inside", None)
maxHumidity = maxHumidity[:-1]
maxHumidity = float(maxHumidity)

minHumidity = firebase.get("/Controls/Sensors/Humidity/min_inside", None)
minHumidity = minHumidity[:-1]
minHumidity = float(minHumidity)

#retrieve max & min temperature (remove the C)
maxTemperature = firebase.get("/Controls/Sensors/Temperature/max_inside", None)
maxTemperature = maxTemperature[:-1]
maxTemperature = float(maxTemperature)

minTemperature = firebase.get("/Controls/Sensors/Temperature/min_inside", None)
minTemperature = minTemperature[:-1]
minTemperature = float(minTemperature)

#add current value
humidity, temperature = readDHT22()
firebase.put("/Controls/Sensors", "/Humidity/current_inside", ""+humidity+"%")
firebase.put("/Controls/Sensors", "/Temperature/current_inside", ""+temperature+"C")

##check for max values
if humidity > maxHumidity:
    firebase.put("/Controls/Sensors", "/Humidity/max_inside", ""+humidity+"%")
    print("Updating Humidity max_inside")
if temperature > maxTemperature:
    firebase.put("/Controls/Sensors", "/Temperature/max_inside", ""+temperature+"C")
    print("Updating Temperature max_inside")

## cehck for min values
if humidity < minHumidity:
    firebase.put("/Controls/Sensors", "/Humidity/min_inside", ""+humidity+"%")
    print("Updating Humidity min_inside")
if temperature < minTemperature:
    firebase.put("/Controls/Sensors", "/Temperature/min_inside", ""+temperature+"C")
    print("Updating Temperature min_inside")

试图使用浮动,但似乎仍然无法正常工作!不会进入最小的ifs。

1 个答案:

答案 0 :(得分:1)

您正在将字符串与浮点数进行比较。

minTemperaturemaxTemperatureminHumiditymaxHumidity都是float个对象,因为您转换了它们。但是temperaturehumidity字符串,因为当您尝试将其与其他字符串连接时,Python会抛出异常。

通过在测试中转换来比较floatfloat

if float(humidity) > maxHumidity:

等。或者将humiditytemperature转换为浮点数并在插入Firebase时将它们转换回字符串。

在Python 2中,始终对不同类型的对象进行一致排序,其中数字优先于其他类型。这意味着<>比较基于两个操作数的排序顺序为真或假,并且因为Python 2中的数字首先排序,所以与另一个类型的任何比较都使用所考虑的数字来完成

>>> 3.14 < "1.1"
True

Python 3不再试图让所有东西都可以订购;将float与字符串进行比较会给您一个TypeError异常。