-2

For example
if test == 1: x = 1; y = 1; z = 2
Would it be possible to not have the z = 2 within the if statement, while keeping it on the same line? Was just wondering if there was a way to do it, similar to how \ continues a line or ; ends one.

Sam
  • 1

1 Answers1

2

Semi-colons only appear in one place in Python's grammar, as part of a simple statement:

simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE

One place a simple statement occurs is in the definition of a suite:

suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

And a suite is the one and only thing that can comprise the body of an if statement:

if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]

From this, we can conclude that the only way to terminate the body of the if statement is with a newline or a DEDENT token. Since a DEDENT token can only occur with an INDENT token, which must follow a newline, you can see there is no way to put a statement that follows an if statement on the same line as the if itself.

chepner
  • 497,756
  • 71
  • 530
  • 681