python - 打印 4 个季节
问题描述
必须编写一个程序,当您输入月份和日期时,它将输出正确的季节。
每个季节的日期是:春季:3月20日 - 6月20日
夏季:6 月 21 日 - 9 月 21 日
秋季:9月22日-12月20日
冬季:12 月 21 日 - 3 月 19 日
如果它与上述任何内容都不匹配,则打印“无效”
input_month = input()
input_day = input()
if input_month in ('April', 'May'):
print('spring')
elif input_month in ('July', 'August'):
print('summer')
elif input_month in ('October', 'November'):
print('autumn')
elif input_month in ('January', 'February'):
print("winter")
elif input_month == 'June' and (input_day == range(1, 20)):
print("spring")
elif input_month == 'June' and (input_day == range(21, 30)):
print("summer")
elif input_month == 'September' and (input_day == range(1, 21)):
print("summer")
elif input_month == 'September' and (input_day == range(22, 30)):
print("autumn")
elif input_month == 'December' and (input_day == range(1, 20)):
print("autumn")
elif input_month == 'December' and (input_day == range(21, 31)):
print("winter")
elif input_month == 'March' and (input_day == range(1, 19)):
print("winter")
elif input_month == 'March' and (input_day == range(20, 31)):
print("spring")
else:
print("invalid")
如果我从没有“和”的行中输入任何内容,它就完美了。我试过括号,改变语句的顺序。任何包含“and”语句的内容都会打印“Invalid”
我尝试将 and 语句的第二个输入的“==”更改为“in”,但输出仍然无效。我尝试将一些 elif 语句更改为 if,但仍然无效。
解决方案
elif input_month == 'June' and (input_day == range(1, 20)):
我在这里看到两个问题:
将值与范围进行比较总是错误的——值是
in
范围,不等于它。input_day
是一个字符串;该范围仅包括数字,因此该值无论如何都不会在该范围内。
你想要的是:
elif input_month == 'June' and int(input_day) in range(1, 20):
另一种更简单的表示方式是… and int(input_day) <= 20
.
推荐阅读
- python - Web Scraping API - “请参阅滚动 API 以更有效地请求大型数据集。”
- python - 熊猫可以自动检测不同的日期时间格式
- c# - 为什么此代码中 LINQ 的扩展方法会打印出一个数字,而根本不应该打印任何内容?
- javascript - 如何将 Angular Predicate 接口与逻辑运算符( AND/OR )一起使用?
- javascript - 使用 jQuery 调整 div 的背景图像大小
- javascript - Chrome 扩展:TypeError:无法读取 null 的属性“addEventListener”
- video - 在nuxt js中动态更改视频标签的src
- flutter - 颤振列表
不是 FutureOr 类型的子类型 - >
- r - R 编程:调用 R 程序我在使用 png() 函数时收到错误
- openvpn - 选择 IP 地址的 openvpn 隧道速度较慢