Library contents

Python SyntaxError

Compile a small piece of source to distinguish invalid syntax from a failure during execution.

A simple example

SyntaxError

  1. Start with Python text with an unclosed parenthesis
  2. Do this Compile the text
  3. Result Syntax error
The parser detects the missing closing parenthesis before the code can run.

Syntax

Python syntax
compile(source, filename, "exec")
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Identify a syntax error in a saved rule

A saved rule is read back before it can be applied to new records. Distinguish a mistake in the rule's syntax from a failure that happens later when valid code is running.

From the programsource = "if total > 5 print(total)"
Resultreceipt_rule.py, line 1
lesson.py
source = "if total > 5 print(total)"
try:
    compile(source, "receipt_rule.py", "exec")
except SyntaxError as problem:
    print(f"{problem.filename}, line {problem.lineno}")
Output
receipt_rule.py, line 1

The rule is missing a colon. Compilation detects the error before the rule can execute.

Advertisements

Review a student’s display line

A pupil double-checks a complete print statement before a demo. Check the example source before running any statements. Will the Python version parse?

Givenprint(7)
Worked resultParses

Catch a missing parenthesis

An editor saves an unfinished statement from a classroom script. Check the example source before running any statements. Will the Python version parse?

Givenprint(7
Worked resultFix syntax

What to watch for

Python exposes a SyntaxError exception. PHP reports parse diagnostics using its own error categories.

Documentation for SyntaxError