What is the Pythonic solution for the next?
I am reading a temperature sensor with a resolution of .5. I need to write (it has a programmable thermostat output), also with a resolution of .5.
So, I wrote this function (Python 2.7) to round a float as input to the nearest .5:
def point5res(number): decimals = number - int(number) roundnum = round(number, 0) return roundnum + .5 if .25 <= decimals < .75 else roundnum print point5res (6.123) print point5res(6.25) print point5res(6.8)
Which works great, outputs 6.0, 6.5 and 7.0, respectively. This is what I want.
I am relatively new to Python. Line
return roundnum + .5 if .25 <= decimals < .75 else roundnum
makes me drool with admiration for its developers. But is it Pythonic?
Edit: after posting, I learned a little more about what it is and is not "Pythonic" . My code is not. Cmd, below, is. Thanks!
source share