What are some other way to rewrite this if block?

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Mar 18 15:32:03 CET 2013

----- Original Message -----
> 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.
> --
> http://mail.python.org/mailman/listinfo/python-list

You can remove the 'if' line, report_status asks for hours, the caller is supposed to provide valid hours. What if the caller gives you strings, integer, floats ?  This is a never ending story.

def report_status(should_be_on, came_on):

    # well if you really really want to test it
    assert(all([int(arg) in range(0,24) for arg in (should_be_on, came_on)])) 

    return { 0 : 'on time', -1 : 'delayed', 1 : 'early'}[cmp(should_be_on, came_on)]


Note : in my example, 24.0 is excluded from the valid durations but I think this is the correct behavior.


The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.

More information about the Python-list mailing list