Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,22 @@ Improved error messages
^^^^^^^
ValueError: too many values to unpack (expected 3, got 4)

* `elif` statements that follow an `else` block now have a specific error message.
(Contributed by Steele Farnsworth in :gh:`129902`.)

.. code-block:: pycon

>>> if who == "me":
... print("It's me!")
... else:
... print("It's not me!")
... elif who is None:
... print("Who is it?")
File "<stdin>", line 5
elif who is None:
^^^^
SyntaxError: 'elif' block follows an 'else' block


* When incorrectly closed strings are detected, the error message suggests
that the string may be intended to be part of the string. (Contributed by
Expand Down
1 change: 1 addition & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -1399,6 +1399,7 @@ invalid_elif_stmt:
invalid_else_stmt:
| a='else' ':' NEWLINE !INDENT {
RAISE_INDENTATION_ERROR("expected an indented block after 'else' statement on line %d", a->lineno) }
| 'else' ':' block 'elif' { RAISE_SYNTAX_ERROR("'elif' block follows an 'else' block")}
invalid_while_stmt:
| 'while' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
| a='while' named_expression ':' NEWLINE !INDENT {
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,18 @@
...
SyntaxError: 'break' outside loop

elif can't come after an else.

>>> if a % 2 == 0:
... pass
... else:
... pass
... elif a % 2 == 1:
... pass
Traceback (most recent call last):
...
SyntaxError: 'elif' block follows an 'else' block

Misuse of the nonlocal and global statement can lead to a few unique syntax errors.

>>> def f():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`elif` statements that follow an `else` block now have a specific error message.
Loading
Loading