首页 > 解决方案 > 打印 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,但仍然无效。

标签: python

解决方案


elif input_month == 'June' and (input_day == range(1, 20)):

我在这里看到两个问题:

  1. 将值与范围进行比较总是错误的——值是in范围,不等于它。

  2. input_day是一个字符串;该范围仅包括数字,因此该值无论如何都不会在该范围内。

你想要的是:

elif input_month == 'June' and int(input_day) in range(1, 20):

另一种更简单的表示方式是… and int(input_day) <= 20.


推荐阅读