PyGCSE Python Lab

BNF Syntax Checker

Write BNF production rules and test whether strings belong to the language. Edit the grammar, change the start symbol, and add test strings to explore context-free grammars. Spec reference: §4.4.3.

📖 Learn Step-by-Step

A simple integer: an optional sign followed by one or more digits.

4 rules parsed · Non-terminals: <integer>, <sign>, <digits>, <digit>

BNF syntax:

<name> — non-terminal (variable)

::= — "is defined as"

| — separates alternatives ("or")

Anything not in angle brackets is a terminal (literal character)

Test Strings

"42"VALID
"-7"VALID
"+100"VALID
"0"VALID
"abc"INVALID
"12.5"INVALID
ε (empty)INVALID
"-"INVALID

BNF / Context-Free Grammar Practice Questions

Q1

Given the BNF rule <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9, how many alternatives does this rule have?

0/1 mark
Q2

The grammar is: <S> ::= a<S>b | ab. What is the length of the shortest string that can be derived from <S>?

0/1 mark
Q3

Using the grammar <S> ::= a<S>b | ab, how many derivation steps are needed to produce the string "aaabbb"?

0/2 marks
Q4

A grammar has: <expr> ::= <term> | <expr>+<term>, <term> ::= <digit>, <digit> ::= 0|1|...|9. How many non-terminal symbols are in this grammar?

0/1 mark
Q5

A BNF grammar generates the language {aⁿbⁿ | n ≥ 1}. Using the rule <S> ::= a<S>b | ab, what is the length of the string generated after exactly 5 derivation steps?

0/2 marks
Quick reference — BNF & Context-Free Grammars

What is BNF?

Backus–Naur Form (BNF) is a notation for describing the syntax of context-free grammars. Each rule defines how a non-terminal can be expanded into a sequence of terminals and/or non-terminals.

BNF notation

<name>Non-terminal (a variable that can be expanded)
::="Is defined as"
|Separates alternatives
terminalsLiteral characters that appear in the final string

Context-free vs regular

Context-free grammars (CFGs) are more powerful than regular expressions. CFGs can describe languages like aⁿbⁿ (matched parentheses) which regular expressions cannot. However, CFGs cannot describe all possible languages — for example, aⁿbⁿcⁿ requires a context-sensitive grammar.

Derivation

A derivation shows how a string is produced from the start symbol by repeatedly replacing non-terminals using the production rules. A leftmost derivation always expands the leftmost non-terminal first.

AQA exam tips

  • Be able to read BNF and determine if a string is valid
  • Be able to write BNF rules for a given language
  • Show derivations step by step
  • Know the difference between BNF and EBNF (Extended BNF uses { } for repetition and [ ] for optional)