How to use "while" within the command in -c option of python?

Chris Angelico rosuav at gmail.com
Sat Oct 13 13:23:25 EDT 2012


On Sun, Oct 14, 2012 at 3:38 AM, Joshua Landau
<joshua.landau.ws at gmail.com> wrote:
> This here isn't a flaw in Python, though. It's a flaw in the command-line
> interpreter. By putting it all on one line, you are effectively saying:
> "group these". Which is the same as an "if True:" block, and some things
> like Reinteract even supply a grouping block like "build".
>
> That said, because some shells suck it would be nice if:
>>
>> python -c "a=1\nif a:print(a)"
>
> worked (just for -c).

Yes, that'd be nice. But it still leaves the big question of why
Python requires \n to separate one statement from another. It IS a
flaw in Python that it requires one specific statement separator in
this instance, even though it'll accept two in another instance.

Here's a side challenge. In any shell you like, start with this
failing statement, and then fix it without retyping anything:

sikorsky at sikorsky:~$ python -c "a=1; if a: print(a)"
  File "<string>", line 1
    a=1; if a: print(a)
          ^
SyntaxError: invalid syntax

In bash, I was unable to insert a newline into the quoted string. My
only option was to backspace everything after the point where I wanted
the newline, then hit enter, then retype the if. I'm curious to know
if that's simply because I didn't think of (some bash feature), or
alternatively, if there's another shell that would have made this
easy.

Back to the main point. In C-like languages, the newline is nothing
special. (ECMAScript allows the omission of semicolons at end of line
in many cases, but many style guides recommend using them anyway.) You
can, if you so desire, put all your code into a single line. It's then
up to the project's style guide to decide how things should be laid
out. For instance, this is multiple statements in PHP, but I see it as
one logical action:

$bar=array(); for ($foo as $k=>$v) $bar[$k]="<p>".$v."</p>";

It's one statement in Python:

bar = ["<p>"+x+"</p>" for x in foo]

It's one statement in Pike:

array bar = map(foo,lambda(string x) {return "<p>"+x+"</p>";});

So it should be allowed to be put on one line. And in languages whose
syntax derives from C, you almost certainly can. (I can't think of any
counter-examples, though that certainly doesn't prove they don't
exist.) But the same thing is forced onto two lines in Python, and not
for syntactic reasons - at least, not that I can see. Perhaps someone
can enlighten me.

Is there any fundamental reason that the syntax couldn't be expanded
to permit "statement; statement" for any two given statements?

ChrisA



More information about the Python-list mailing list