如果所选索引大于最大索引,程序将继续以滚动形式(python)对索引进行计数



例如:List["cat", "dog", "wolf", "mouse", "fish"]有5个单词。用户选择了索引8程序将以循环方式计数并到达索引2或单词"0";"狼";再一次

您可以使用mod(%(运算符。

下面的代码可以帮助解决您的问题

list = ["cat", "dog", "wolf", "mouse", "fish"]
list_len = len(list) # calculate list length
index = int(input("input an index"))
print(list[(index % list_len) - 1]) # In python, arrays start at 0. So we subtract 1

最新更新