Python如何通过列表匹配用户输入的月份数获取对应天数
核心问题梳理
你原有代码存在两个逻辑错误:
- 索引对应关系错误:给定的
days列表索引从0开始,依次对应1-12月,用户输入的月份值减1即可直接匹配days列表的索引,不需要循环遍历 - 判断逻辑混淆:错误地将
days列表存储的天数值和用户输入的月份数值做相等判断,完全搞混了两个变量的含义
解决方案
仅通过列表操作即可实现,不需要引入任何第三方库,我们只需要新增一个和days列表索引一一对应的月份名称列表即可:
def getValidMonth(): userInput = 0 while userInput < 1 or userInput > 12: userInput = int(input("Please enter the valid number of month: ")) return userInput def findDays(userInput): days = [31,28,31,30,31,30,31,31,30,31,30,31] month_names = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] index = userInput - 1 print(f"{month_names[index]} has {days[index]} days") def main(): userInput = getValidMonth() findDays(userInput) main()
逻辑说明
month_names列表的顺序和给定的days列表完全对齐,索引0对应1月,索引1对应2月,以此类推- 拿到合法的用户输入月份后,直接减1得到对应列表的索引,取值拼接输出即可,逻辑简洁执行效率高
- 完全基于原生列表操作实现,严格使用了题目给定的
days列表查询天数,符合需求
可选优化:如果需要支持闰年2月29天的场景,可以在获取到用户输入月份为2时,额外增加年份输入,补充闰年判断逻辑调整天数即可
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

