Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #41427
| Date | 2013-03-18 15:32 +0100 |
|---|---|
| From | Jean-Michel Pichavant <jeanmichel@sequans.com> |
| Subject | Re: What are some other way to rewrite this if block? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3454.1363617125.2939.python-list@python.org> (permalink) |
----- 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)]
JM
Note : in my example, 24.0 is excluded from the valid durations but I think this is the correct behavior.
-- IMPORTANT NOTICE:
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.
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: What are some other way to rewrite this if block? Jean-Michel Pichavant <jeanmichel@sequans.com> - 2013-03-18 15:32 +0100 Re: What are some other way to rewrite this if block? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-03-18 15:07 +0000
csiph-web