1

I don't understand why I'm having an error with Python when I use a single-line if statement after a semicolon (used as a statement separator).

This is ok:

if True: print("it works")
#### it works

But this gives a syntax error:

a=1; if True: print("it should work?")
#### SyntaxError: invalid syntax

I use Python3, with Spyder.

Thanks for any explanation!

agenis
  • 8,069
  • 5
  • 53
  • 102
  • This doesn't work with any [compound statement](https://docs.python.org/3/reference/compound_stmts.html) as the clause header needs to be on it's own line. – a_guest Mar 31 '19 at 23:01

1 Answers1

2

Semicolons can only be used to join "small statements", which don't include if statements. From https://docs.python.org/3/reference/grammar.html:

stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)

[...]
compound_stmt: if_stmt | [...]
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks, didn't know about that! – agenis Mar 31 '19 at 23:12
  • Clearly, something like `if foo: x=1; y=2` is ambiguous given Python's use of indentation. I suspect there's no ambiguity in `a=1; if True: print("it should work")`. However, it probably isn't worth complicating the grammar to support it. (Or it might not be possible given Python's self-imposed constraint of using an LL(1) grammar.) – chepner Mar 31 '19 at 23:21