Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit99b71ef

Browse files
authored
gh-129858: Special syntax error forelif block afterelse (#129902)
1 parentc3a7118 commit99b71ef

File tree

5 files changed

+137
-75
lines changed

5 files changed

+137
-75
lines changed

‎Doc/whatsnew/3.14.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,21 @@ Improved error messages
348348
^^^^^^^
349349
ValueError: too many values to unpack (expected3, got4)
350350
351+
*:keyword:`elif` statements that follow an:keyword:`else` block now have a specific error message.
352+
(Contributed by Steele Farnsworth in:gh:`129902`.)
353+
354+
..code-block::pycon
355+
356+
>>> if who == "me":
357+
... print("It's me!")
358+
... else:
359+
... print("It's not me!")
360+
... elif who is None:
361+
... print("Who is it?")
362+
File "<stdin>", line 5
363+
elif who is None:
364+
^^^^
365+
SyntaxError: 'elif' block follows an 'else' block
351366
352367
* If a statement (:keyword:`pass`,:keyword:`del`,:keyword:`return`,
353368
:keyword:`yield`,:keyword:`raise`,:keyword:`break`,:keyword:`continue`,

‎Grammar/python.gram

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1422,6 +1422,7 @@ invalid_elif_stmt:
14221422
invalid_else_stmt:
14231423
| a='else' ':' NEWLINE !INDENT {
14241424
RAISE_INDENTATION_ERROR("expected an indented block after 'else' statement on line %d", a->lineno) }
1425+
| 'else' ':' block 'elif' { RAISE_SYNTAX_ERROR("'elif' block follows an 'else' block")}
14251426
invalid_while_stmt:
14261427
| 'while' named_expression NEWLINE { RAISE_SYNTAX_ERROR("expected ':'") }
14271428
| a='while' named_expression ':' NEWLINE !INDENT {

‎Lib/test/test_syntax.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -948,6 +948,18 @@
948948
...
949949
SyntaxError: 'break' outside loop
950950
951+
elif can't come after an else.
952+
953+
>>> if a % 2 == 0:
954+
... pass
955+
... else:
956+
... pass
957+
... elif a % 2 == 1:
958+
... pass
959+
Traceback (most recent call last):
960+
...
961+
SyntaxError: 'elif' block follows an 'else' block
962+
951963
Misuse of the nonlocal and global statement can lead to a few unique syntax errors.
952964
953965
>>> def f():
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
``elif`` statements that follow an ``else`` block now have a specific error message.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp