如果x是从1?
开始的任何正整数,那么如何编写以下内容呢?if x == 1:
n = 1
elif 2 <= x <= 5:
n = 2
elif 6 <= x <= 9:
n = 3
elif 10 <= x <= 13:
n = 4
elif 14 <= x <= 17:
n = 5
......等等......
答案 0 :(得分:8)
你不需要if
或循环,这是一个简单的,封闭形式的数学关系:
n = 2 + (x - 2)/4
顺便说一句,您不需要在elif
语句中测试范围的两端。由于它们是按顺序执行的,因此您知道该数字大于范围的底部,因此它只是:
if x == 1:
n = 1
elif x <= 5:
n = 2
elif x <= 9:
n = 3
... and so on