Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
EBNF: Some Python constructs


1. EBNF: Some Python constructs

2. EBNF for some Python constructs
One can learn a lot about a programming language by inspecting the grammar and investigating parts of the language that one may never have encountered before.

3. Python grammar
The official Python EBNF grammar is at https://docs.python.org/3/reference/grammar.html .

There may be parts of this grammar that you have never encountered.

Studying the grammar of a language can help discover parts of the language that might be useful. Or that one might find used in examples on the Internet. Here are some EBNF rules for the grammar of the Python programming language, reformatted some from the official on-line grammar, that might be interesting.

4. Conditional statement
Here is the associated EBNF (Extended Backus Naur Form) syntax diagram(s).

Syntax diagram for EBNF
Here is the associated EBNF grammar.
if_stmt = "if" then_part { elif_part } [ else_part ] . then_part = namedexpr_test ":" suite . elif_part = "elif" namedexpr_test ":" suite . else_part = "else" ":" suite .


5. While statement
Here is the associated EBNF syntax diagram(s).

Syntax diagram for EBNF
Here is the associated EBNF grammar.
while_stmt = "while" namedexpr_test ":" suite [ "else" ":" suite ] .

Did you know the Python while loop has an optional else part?

6. Else part of a while statement
The else part of a Python while statement executes once whenever the while loop condition is or becomes false. It does not execute on a break out of the loop or if an exception is raised.

One use of this is to make it easier to break out of multiple levels of loops.

On the other hand, features that are not easily portable to other programming language may need to be used with some caution. Here is the Python code.

Here is the output of the Python code.


7. Break from inside nested loop
Here is an example that shows how one might break outside a nested loop from within the inner loop using a while-else.

Is a clear way to do this? Here is the Python code.

Here is the output of the Python code.


8. For loop
Here is the associated EBNF syntax diagram(s).

Syntax diagram for EBNF
Here is the associated EBNF grammar.
for_stmt = "for" exprlist "in" testlist ":" [ TYPE_COMMENT ] suite [ "else" ":" suite ] .

Did you know the Python for loop has an optional else part? It is similar in purpose as in the while loop.

And what exactly is a TYPE_COMMENT?

9. End of page

10. Acronyms and/or initialisms for this page