What are some other way to rewrite this if block?

Jussi Piitulainen jpiitula at ling.helsinki.fi
Mon Mar 18 10:10:07 EDT 2013


Santosh Kumar <sntshkmr60 at gmail.com> writes:

> This simple script is about a public transport, here is the code:
> 
> def report_status(should_be_on, came_on):
>     if should_be_on < 0.0 or should_be_on > 24.0 or came_on < 0.0 or
> came_on > 24.0:
>         return 'time not in range'
>     elif should_be_on == came_on:
>         return 'on time'
>     elif should_be_on > came_on:
>         return 'early'
>     elif should_be_on < came_on:
>         return 'delayed'
>     else:
>         return 'something might be wrong'
> 
> print(report_status(123, 12.0))
> 
> I am looking forward of make the line starting with `if` short.
> 
> Any tips are welcome.

A double tip:

if (not (0.0 <= should_be_on <= 24.0) or
    not (0.0 <= came_on <= 24.0)):
   ...

You might want to raise an exception from the range-check branch
instead of returning a value. And raise an exception from the
else-branch, because that branch should never be reached.



More information about the Python-list mailing list