我一直在尝试在业余时间编写一个简单的日历作为编码练习。但是,我似乎无法解决此问题:
如何返回列表中的项目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
?
答案 0 :(得分:1)
您可以使用模数:
dayoftheweek = days[userchoice % len(days)]