No, you canβt . The Python language reference reads:
Compound statements consist of one or more. "A sentence consists of a heading and a set. Article headings for a particular compound expression are still indented. Each sentence heading begins with a unique keyword identification and ends with a colon. A suite is a group of statements controlled by an item. A set can be one or more semicolon-separated simple statements on the same line as the heading, after the colon headers, or there may be one or more indentation . on subsequent lines in only the last set of the form can contain nested compound statements: illegally, mainly because it was not clear to which if the else clause would belong:
if test1: if test2: print x
Indeed, Python throws a SyntaxError for the nested ifs above. More formally relative to for , this is his grammar in Python:
for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
Note that for follows an stmt_list statement; this statement must be stmt_list , which allows only instances of simple_stmt . simple_stmt :
simple_stmt ::= expression_stmt | assert_stmt | assignment_stmt | augmented_assignment_stmt | pass_stmt | del_stmt | print_stmt | return_stmt | yield_stmt | raise_stmt | break_stmt | continue_stmt | import_stmt | global_stmt | exec_stmt
which does not contain compound statements such as if and for .
However, keep in mind that Python syntax is aimed at clarity. Therefore, it is better not to embed such statements, this is what was done to understand generators / lists. If you think your calculations are simple enough for one line, then there is an understanding for you. Otherwise, you really do not want to clutter up the code, having everything in one line - perfectly open it with indentation. A few extra lines these days are not so expensive.
Eli bendersky
source share