I see why this would be questionable:

1. operator precedence.
2. grammar rules.

If we are talking about operator precedence, it's hard to tell without
consulting the manual (and even then?) what happens first. "else" is
allowed in "strange" places in Python, eg.

    for var in iterator:
    else:
        statement

with the intention of executing the "statement" when the loop exits
early. So, it's possible that there's some other interpretation of the
code, where "else" is used in the "head" of the loop statement, that
is just seldom used.

When grammar rules are concerned, It could be expected that the code
in question would either generate a syntax error because the
"iterator" part of the loop may not be a general expression, or that
the whitespace has different meaning in this context (the meaning of
whitespace varies in Python's grammar rules based on the context:
sometimes it's optional, other times it's essential).

In either case, I'd avoid writing code like that because it's too
unusual. It's longer, but a lot more typical to write code like:

    iterator = choice_a if condition else choice_b
    for var in iterator:
        statement


On Wed, May 13, 2026 at 10:39 PM Michael F. Stemper via Python-list
<[email protected]> wrote:
>
> I have a program that does some calculations for multiple
> different values of a certain quantity. I wanted to either
> write a second program that would hold the first quantity
> fixed and loop over a different one, or to extend the
> first to do either of those based on a command-line option.
>
> While noodling around, I thought "what about --" and came up
> with the following idea:
>
> ============================================================
> if options.angle:
>    angles = [0.05*k for k in range(7)]
> else:
>    comps = [0.1*k for k in range(6)]
>
> for variable in angles if options.angle else comps:
>    if options.angle:
>      angle = variable
>    else:
>      X_C = variable * -X_L
>
>    junk = sys.stdout.write( "%4.2f  %4.3f\n" % (angle,X_C) )
>    # Hard part elided for clarity
> ============================================================
>
> I was surprised to see that one could actually write a
> for-loop like that, although it tickled my inner hacker.
>
> What I'd like to know is: Is this an egregious abuse of the
> language, or is it perfectly pythonic?
>
> Opinions, and even violent disagreement, are solicited.
>
> --
> Michael F. Stemper
> Always use apostrophe's and "quotation marks" properly.
> --
> https://mail.python.org/mailman3//lists/python-list.python.org
-- 
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to