Skip to content Skip to sidebar Skip to footer

Simple Python If Statement Does Not Seem To Be Working

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 for max values if humidi

Solution 1:

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.

Post a Comment for "Simple Python If Statement Does Not Seem To Be Working"