Reputation: 10855
python -c 'for i in range(10): print i'
works, and
python -c 'a=3;'
works, but
python -c 'a=3;for i in range(10): print i'
gave an error
File "<string>", line 1
a=3;for i in range(10): print i
^
SyntaxError: invalid syntax
Could anyone help point out why? Thank you.
Upvotes: 2
Views: 82
Reputation: 198324
Because that's how Python syntax works. for
, like all other statements that introduce an indent level, does not like having anything in front of it.
You need a newline in this case, not a semicolon. These are legal (assuming bash
):
python -c 'a=3
for i in range(10)]: print(i)'
python -c $'a=3\nfor i in range(10): print(i)'
Upvotes: 5
Reputation: 6866
;
can only be used to separate "simple" statements, not compound statements.
https://docs.python.org/3/reference/compound_stmts.html
compound_stmt ::= if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| async_with_stmt
| async_for_stmt
| async_funcdef
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement ::= stmt_list NEWLINE | compound_stmt
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
Upvotes: 4