if isLeapYear:
if month == 2:
return 29
elif month == 4 or month == 6 or month == 9 or month == 11:
return 30
else:
return 31
else:
if month == 2:
return 28
elif month == 4 or month == 6 or month == 9 or month == 11:
return 30
else:
return 31
我希望这些if else语句缩短if和else语句中的else if和else语句是相同的有什么办法可以缩短这些
只能使用if..else语句并返回条件操作的结果
isLeapYear = True
def getMonthDays (month):
if month == 2:
return 29 if isLeapYear else 28
else:
return 30 if month == 4 or month == 6 or month == 9 or month == 11 else 31
print(getMonthDays(2)) # 29
print(getMonthDays(4)) # 30
print(getMonthDays(12)) # 31
条件(三元运算)为:return "yes" if Statement else "no"
进一步简化较长的行:
isLeapYear = True
def getMonthDays (month):
if month == 2:
return 29 if isLeapYear else 28
else:
return 30 if month in [4, 6, 9, 11] else 31
print(getMonthDays(2)) # 29
print(getMonthDays(4)) # 30
print(getMonthDays(12)) # 31
并没有真正简化if/else结构,但很可能是问题本身的更简单解决方案。除非这是作业;)
import calendar
_weekday, nof_days = calendar.monthrange(1999,2)
print(nof_days)
=比;28日
详情请参阅Python文档。
假设isLeapYear返回True或False,你可以试试下面的逻辑,
if isLeapYear==True and month == 2:
return 29
elif isLeapYear==False and month == 2:
return 28
elif (isLeapYear==True or isLeapYear==False) and month in [4,6,9,11]:
return 30
else:
return 31