python - problem with if else loop for a month and days problem
问题描述
why do I get the wrong output for the code below, I've put the output below
(some might suggest using date-time module, I'm going with this method due to some complications with the main program)
months = [1,2,3,4,5,6,7,8,9,10,11,12]
for month in months:
if month == {1,3,5,7,9,11}:
days= 31
print(days)
elif month == {4,6,8,10,12}:
days = 30
print(days)
else :
days = 28
print(days)
I get this output
28
28
28
28
28
28
28
28
28
28
28
28
解决方案
Question approach
You are checking if an integer is equal to a set. You want to check if the integer is in the set. By the way, the sets you use are wrong (fixed here) and february may have 29 days (not fixed in this solution).
for month in range(1, 13):
if month in {1, 3, 5, 7, 8, 10, 12}:
days = 31
elif month in {4, 6, 9, 11}:
days = 30
else :
days = 28
print(f"{month:2}: {days}")
1: 31
2: 28
3: 31
4: 30
5: 31
6: 30
7: 31
8: 31
9: 30
10: 31
11: 30
12: 31
Calendar approach
Another solution is to use the calendar
module which fixed the 29 days on february issue.
import calendar
for month in range(1, 13):
days = calendar.monthrange(2020, month)[1]
print(f"{month:2}: {days}")
1: 31
2: 29
3: 31
4: 30
5: 31
6: 30
7: 31
8: 31
9: 30
10: 31
11: 30
12: 31
推荐阅读
- angular - 同一组件内的角度动画
- c++ - 类图中接口和类所需的关系,C++
- maven - maven中的传递依赖
- python - 合并具有不同和未知字段的数据帧
- linux - foreach 循环中的 TCSH 错误:files.list:找不到命令
- javascript - 如何将复杂的字符串拆分为数组?
- javascript - 如何通过过滤器在具有行跨度的表中进行搜索
- fabricjs - Fabricjs v2.4.1 loadFromJSON 从 v1.7.17 生成的图像缩放问题
- facebook - 将应用程序公开后发布到页面不起作用
- asp.net - Asp net core api 循环实体未显示在循环结果中