根据一系列数字进行打印



基于一系列数字打印时遇到问题。如何使此命令更高效或更有效?

假设低通胀率低于3%,中等通胀率为3%或更高但低于5%,高通胀率超过5%但低于10%,任何10%或更高的通胀率都是超通胀。

if inf_Rate <= 3:
print("Type of inflation: Low")
elif inf_Rate in range(3, 5):
print("Type of inflation: Moderate")
elif inf_Rate in range(5, 10):
print("Type of inflation: High")
else:
print(("Type of inflation: Hyper"))

如果数字是浮动的,只使用普通比较,而不是in range()

if inf_Rate < 3:
inf_type = 'Low'
elif inf_Rate < 5:
inf_type = 'Moderate'
elif inf_rate < 10:
inf_type = 'High'
else: 
inf_type = 'Hyper'
print(f'Type of inflation: {inf_type}')

您不需要测试每个范围的底部,因为条件是按顺序测试的,并且已经排除了较低的值。

此外,你的第一个条件与给定条件不匹配。它应该低于3%,但你的情况包括3%。

内置的range仅适用于int,但定义自己的InflationRateRange类相对容易,其中__contains__封装了链式比较方法。

class InflationRateRange(object):
def __init__(self, low, high):
self.low = low
self.high = high
def __contains__(self, val):
return self.low <= val <= self.high

现在你可以使用浮点数了。

2.7 in InflationRateRange(0, 3)
# True

最新更新