Reputation: 213
I am currently learning Python and want to ensure I am using good python practices and need some help in finding the best way of checking whether a value falls between different ranges.
Basically I am trying to find whether a cpu utilization is between 0-33 (green), 34-66 (amber) or 67-100 (red). Here's my current code;
green = 33
amber = 66
red = 100 # Probably not needed, but there for completeness
if cpu <= green:
print "green"
elif cpu > amber:
print "red"
else:
print "amber"
Is there a better way to achieve this in Python?
I've looked at "Interval Comparisons" and that doesn't seem to quite fit the bill - although it is entirely possible that I haven't understood them correctly.
Any help is greatly appreciated.
Upvotes: 3
Views: 157
Reputation: 599628
It's hardly any simpler in your case, but in general you can the bisect
module for comparisons like this.
limits = [33, 66, 100]
names = ['green', 'amber', 'red']
interval = bisect.bisect_left(limits, cpu)
print names[interval]
Upvotes: 2
Reputation: 32094
It's a trivial piece of code, and is readable enough. But if you had more intervals, you would need a loop. Here is an example:
for level_max, level in [(33, 'green'), (66, 'amber'), (100, 'red')]:
if cpu <= level_max:
print level
break
Upvotes: 0
Reputation: 362826
That is fine. This might be more readable, because the order of logic in the code is matching the escalation of levels:
if cpu <= green:
print "green"
elif cpu <= amber:
print "amber"
else:
print "red"
Upvotes: 2