a = 5且b = 8
我需要在for循环中使用这些数字。
for i in range(a, b):
这些将从5到8开始
如果我使用如下
for i in (a, b):
这些将打印5和8。
现在我需要你的帮助,如果a = 5和8意味着我需要找到5到8之间的范围是1到4并且形成循环1到4
如果a = 3且5意味着我需要找到3到5之间的范围是1到3,并形成循环1到3。
答案 0 :(得分:1)
range(a, b)
会返回b - a
个值列表,而(a, b)
是一个只有两个值的元组。
要解决您的问题,您可以这样做。
for x in range(a, b + 1): # +1 to include the end of the range in the list
x = x - a + 1; # Make x start at 1
...
或者
for x in range(1, b - a + 2): # +1 to include end of range, +1 again since range start at 1
...
或(如DeepSpace所述)
for x in range(b - a + 1): # +1 to include the end of the range
x = x + 1 # Since range should start at 1
...