Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a double semicolon a SyntaxError in Python?

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?

like image 400
alexwlchan Avatar asked Mar 20 '16 09:03

alexwlchan


2 Answers

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 
like image 125
Aaron Christiansen Avatar answered Oct 05 '22 22:10

Aaron Christiansen


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

>>> x = 42;pass; >>> x 42 
like image 37
TigerhawkT3 Avatar answered Oct 05 '22 23:10

TigerhawkT3