我正在编写一个程序,该程序将接受列表作为输入。第一个数字应该是指定的范围。最后一个数字应该是最大值。然后,在指定的范围内,不包括第一个值,输出所有小于或等于最大值的数字。代码在这里:
nums = input().splitlines()
theRange = int(nums[0])
highNum = int(nums[-1])
i = 1
while (i <= theRange) and (i <= len(nums)):
if int(nums[i]) <= theRange:
print(nums[i])
i += 1
输入后:
5
50
60
140
200
75
100
导致的错误是:
Traceback (most recent call last):
File "main.py", line 8, in <module>
if int(nums[i]) <= theRange:
IndexError: list index out of range
这毫无意义,因为theRange变量小于nums的长度。请告诉我为什么会发生这种事。谢谢
Python中的列表是基于零的,因此应该使用<
运算符,而不是<=
:
while (i < theRange) and (i < len(nums)):