Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -1396,6 +1396,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 @@ -918,6 +918,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,13 @@
`elif` statements that follow an `else` block now have a specific error message.
```py
>>> 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
```
Loading
Loading