有困难的打印基于一系列的数字。如何使此命令更有效或更有效?
如果通胀率低于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"))发布于 2022-10-07 00:01:25
如果数字是浮动的,只需使用常规比较,而不是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%。
发布于 2022-10-07 00:12:23
内置的range只在it上工作,但是定义自己的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)
# Truehttps://stackoverflow.com/questions/73981046
复制相似问题