Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 15 additions & 0 deletions Doc/whatsnew/3.14.rst
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,21 @@ Improved error messages
^^^^^^^
ValueError: too many values to unpack (expected 3, got 4)

* :keyword:`elif` statements that follow an :keyword:`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

* If a statement (:keyword:`pass`, :keyword:`del`, :keyword:`return`,
:keyword:`yield`, :keyword:`raise`, :keyword:`break`, :keyword:`continue`,
Expand Down
1 change: 1 addition & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,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 @@ -948,6 +948,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.
Copy link
Member

@picnixz picnixz Feb 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:keyword:`elif` statements that follow an :keyword:`else` block now have a specific error message.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also put the keyword syntax here.

Loading
Loading