在1个语句中加入多个ifs

时间:2014-12-04 09:18:22

标签: python if-statement

如果条件

,以下结果是否等同于加入以下内容?
if (now_time > time(19,00) and now_time < time(7,00)):
else if (now_time > time(9,50) and now_time < time(12,00)):
else if (now_time > time(14,30) and now_time < time(16,15)):

结果

if ((now_time > time(19,00) and now_time < time(7,00)) or
    (now_time > time(9,50) and now_time < time(12,00)) or
    (now_time > time(14,30) and now_time < time(16,15))):

2 个答案:

答案 0 :(得分:3)

假设ifelif个案例运行相同的代码,是的,但您也可以:

if (time(19, 00) < now_time < time(7, 00) or 
    time(9, 50) < now_time < time(12, 00) or
    time(14, 30) < now_time < time(16, 15)):

甚至可能是:

if any(time(*start) < now_time < time(*end)
       for start, end in [((19, 0), (7, 0)), ...]):

允许您更轻松地添加和删除案例。

答案 1 :(得分:1)

您可以执行以下操作:if start < now < end:

您的两个示例并不相同,因为您现在将所有案例合并为一个。