Python / Editorial solution guide
Diagnose SyntaxError and IndentationError safely
Use the reported location as evidence, inspect surrounding structure, and verify corrected syntax without executing the program.
Read-only knowledge base · No public comments
Recognize the symptoms
Python refuses to start a file and reports SyntaxError, IndentationError, or TabError. The caret may point at a line that looks reasonable because an earlier delimiter, string, or block is incomplete.
A pasted example may contain interactive >>> prompts or indentation changed by an editor. Preserve the exact error and nearby source rather than repeatedly editing only the highlighted character.
Understand the likely causes
- Common causes include a missing colon after a compound-statement header, unmatched brackets or quotes, an incorrectly aligned block, and mixed tabs and spaces. The indicated position is where parsing became impossible, which can be after the original mistake.
- Syntax from a newer Python version can also fail under an older interpreter. Verify the actual version before rewriting a valid example to fit an unintended environment.
1. Read the entire diagnostic
Record the filename, line number, caret span, and exact exception message. Inspect the reported line and several preceding lines in the saved file, ensuring you are reading the same path that was invoked. Count opening and closing parentheses, brackets, and braces, and check whether a quote continues across the apparent boundary. A parser cannot always identify the human intention behind unfinished input. Fix the first structural problem you can justify, then parse again; later diagnostics may be consequences of that one defect.
2. Reconstruct the intended block
A block header such as if, for, while, def, or class ends with a colon and is followed by an indented suite. Use four spaces per indentation level consistently. Align elif and else with their owning if, and align except and finally with try. Show whitespace in the editor when tabs are suspected. Do not blindly remove all indentation: a syntactically accepted rearrangement can change which statements belong to a branch. The broken fragment below is intentionally non-runnable; its correction preserves a two-statement loop body.
for number in range(2)
print(number)
This is intentionally invalid source for inspection only. Do not run it as a complete example.
for number in range(2):
doubled = number * 2
print(doubled)
0
2
The colon opens the suite and both statements share its indentation. The result demonstrates the intended loop membership.
3. Check syntax without execution
The built-in compile function can parse and compile known source text without executing the resulting code object. Do not pass that code object to exec or eval during a syntax-only diagnosis. The example compiles a small fixed snippet in memory and prints a stable success marker. When checking a real file, read the intended file only and preserve its encoding declaration; source-aware loading tools can respect it. Successful compilation establishes syntactic acceptance for this interpreter, not correct results, safe behavior, or valid imports at runtime.
source = "if True:\n answer = 42\n"
compile(source, "<syntax-check>", "exec")
print("Syntax accepted")
Syntax accepted
The mode string exec selects statement syntax; it does not itself execute the returned code object. No code object is run here.
4. Review meaning after syntax passes
Trace a tiny expected case after reviewing the corrected block structure. Only run source you understand and are authorized to execute in an isolated local context. Test both sides of a branch and the empty-loop case where relevant. A misplaced print can be valid Python while running once after a loop instead of once per item. If compilation still fails, reduce the example while retaining the first reported structural issue and confirm that the interpreter supports the syntax being used.
Verify the fix
The saved source compiles under the intended supported interpreter with no syntax or indentation diagnostic. Reviewed indentation matches the intended control-flow tree.
A small authorized behavior check produces the expected lines on each relevant path. Compilation alone is insufficient to confirm that the repaired indentation preserved meaning.
Keep it from recurring
- Enable consistent spaces, visible whitespace when diagnosing, and bracket matching in the editor. Copy source separately from shell prompts and keep examples compatible with the project’s declared Python version.
- Make one structural correction at a time and rerun the syntax check before changing unrelated logic.