如何保护我的代码免受“索引超出范围”错误的影响

时间:2018-09-05 13:00:34

标签: python arraylist

我一直在尝试在业余时间编写一个简单的日历作为编码练习。但是,我似乎无法解决此问题:

如何返回列表中的项目0?我的想法是,只要星期几长于列表的长度,它就会返回为days [0],但我似乎无法使其正常工作。

days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
dayoftheweek = days[0]

userchoice = int(input("Please add a number to days: "))
dayoftheweek = days[userchoice]

如果用户输入8,我将遇到Index out of range错误。

如何捕获days范围之外的输入并默认为0

1 个答案:

答案 0 :(得分:1)

您可以使用模数:

dayoftheweek = days[userchoice % len(days)]