68

I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g.

>>> x = 42; y = 54

I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t Ned Batchelder on Twitter) that a double semicolon is a SyntaxError:

>>> x = 42
>>> x = 42;
>>> x = 42;;
  File "<stdin>", line 1
    x = 42;;
           ^
SyntaxError: invalid syntax

I assumed the last program was equivalent to x = 42\n\n. I’d have thought the statement between the semicolons was treated as an empty line, a no-op. Apparently not.

Why is this an error?

Oliphaunt
  • 200
  • 9
alexwlchan
  • 5,699
  • 7
  • 38
  • 49
  • 9
    A semicolon is not equivalent to a newline, otherwise stuff like `if condition:;` would also be legal, but it is not. – tobias_k Mar 20 '16 at 09:12
  • @tobias_k No, it would not be legal. You would need a 'pass'. But 'if condition:;pass' doesn't work too. – palsch Mar 20 '16 at 12:15
  • 2
    Why shouldn't it be an error? There's no reason to write code like that and it'll likely confuse whoever reads it next, so isn't making it outright illegal (preventing you from making a typo and thereby leaving your coworkers to wonder what the effect of the double-colon syntax is when they see the code) a helpful thing for Python to do? – Mark Amery Mar 20 '16 at 19:55
  • Would you expect `print [1, 2,, 3]` to work? It's pretty much the same thing. – Luaan Mar 21 '16 at 09:39

2 Answers2

104

From the Python grammar, we can see that ; is not defined as \n. The parser expects another statement after a ;, except if there's a newline after it:

                     Semicolon w/ statement    Maybe a semicolon  Newline
                          \/     \/               \/                \/
simple_stmt: small_stmt (';' small_stmt)*        [';']            NEWLINE

That's why x=42;; doesn't work; because there isn't a statement between the two semicolons, as "nothing" isn't a statement. If there was any complete statement between them, like a pass or even just a 0, the code would work.

x = 42;0; # Fine
x = 42;pass; # Fine
x = 42;; # Syntax error

if x == 42:; print("Yes") # Syntax error - "if x == 42:" isn't a complete statement
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78
  • You could also say it's because the nonterminal small_stmt is not nullable, i.e. the empty string (epsilon) does not match small_stmt. This is the case in other languages. – thwd Mar 23 '16 at 00:40
  • maybe a typo: Syntax error - "if x == **2**:" maybe should be 42? – Ron Klein Apr 05 '16 at 08:27
22

An empty statement still needs pass, even if you have a semicolon.

>>> x = 42;pass;
>>> x
42
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97