Ossama
Ossama

Reputation: 2433

Joining multiple ifs in 1 statement

Will the below result be equivalent to joining the following if conditions

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)):

Result

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))):

Upvotes: 0

Views: 66

Answers (2)

jonrsharpe
jonrsharpe

Reputation: 122032

Assuming the if and elif cases run the same code, yes, but you could also have:

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)):

Or even something like:

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

which allows you to more easily add and remove cases.

Upvotes: 3

orange
orange

Reputation: 8090

You can do something like this: if start < now < end:

Your two examples are not equivalent, as you're now combining all cases into one.

Upvotes: 1

Related Questions