如何在python中正确使用“或”?

时间:2018-12-10 23:49:37

标签: python

我正在尝试将变量numberOfDays设置为等于月份中的天数。但是,elif语句有一个缺陷。我显然没有正确使用“或”语句,因为当我输入任何内容时,它总是说numberOfDays等于30。

   monthSelection = input("Enter the month you wish to view: ")

   if monthSelection == "February":
        numberOfDays = 28
   elif monthSelection == "April" or "June" or "September" or "November":
        numberOfDays = 30
   else:
        numberOfDays = 31

是否有任何方法可以重新格式化此代码以使其起作用?

2 个答案:

答案 0 :(得分:0)

使用in而不是or

if monthSelection == "February":
    numberOfDays = 28
elif monthSelection in ("April", "June", "September", "November"):
    numberOfDays = 30
else:
    numberOfDays = 31

否则,您需要分别指定每个等式:

if monthSelection == "February":
    numberOfDays = 28
elif monthSelection == "April" or monthSelection == "June" or monthSelection == "September" or monthSelection == "November":
    numberOfDays = 30
else:
    numberOfDays = 31

答案 1 :(得分:0)

或者将calendar模块与单线使用:

import calendar
print(calendar.monthrange(2018,list(calendar.month_abbr).index(monthSelection[:3]))[-1])

示例:

Enter the month you wish to view: February
28
>>>