Single line if statement with a continue

Peter J. Holzer hjp-python at hjp.at
Mon Dec 19 07:01:41 EST 2022


On 2022-12-18 16:49:27 +0000, Stefan Ram wrote:
> Dennis Lee Bieber <wlfraed at ix.netcom.com> writes:
> >>for idx, thing in enumerate(things):
> >>    if idx == 103: 
> >>        continue
> >>    do_something_with(thing)
> >>
> >	For this example, I'd probably reverse the condition.
> >	if idx != 103:
> >		do_something_with(thing)
> 
>   The first four lines of the quotation above cannot be a
>   complete program as "do_something_with" is not defined
>   therein, so they must be part of a larger program.
>   If, in this larger program, something still follows
>   "do_something_with(thing)" in the loop, the new program
>   after the transformation might not show the same behavior.

“do_something_with(thing)” is obviously not intended to be a single
function call but as a shorthand for “one or more lines of code which do
something with `thing`”. So there is nothing after it because it is
included in it.

That said, the "fail and bail" technique is often more readable than
putting the main incode inside of an if - especially if that code is
long and/or it is guarded by multiple conditions.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20221219/346beb68/attachment-0001.sig>


More information about the Python-list mailing list