Python Syntax Errors and Logic Errors
Learn to distinguish Python syntax errors from logical errors, read diagnostics, and fix common mistakes with practical examples and debugging techniques.
What Errors Mean in a Python Program
An error is a problem that prevents a program from working as intended. Some errors stop Python before normal execution begins. Other errors allow the program to run, but the output, decision, calculation, or side effect is wrong.
Two foundational categories are syntax errors and logical errors. A syntax error means that the source code does not follow Python's grammar. A logical error means that valid Python code does not express the intended reasoning or algorithm.
The interpreter is the Python program that reads, parses, and executes your code. It detects many syntax problems while parsing the source, before normal execution can proceed.
Syntax Errors
A syntax error is a violation of Python's language grammar. Python cannot understand the structure of the source code, so it normally reports the problem before the affected program starts its ordinary work. The error type is commonly shown as SyntaxError.
For example, this loop header contains a misspelled keyword:
number = int(input("Enter a number: "))
whille number % 2 == 0:
print("The number is even.")
Python reports a syntax error near whille because Python keywords must be spelled exactly. Correcting it to while makes the header syntactically valid, although the loop may still need a condition or update that makes sense for the program's goal.
How to Read a Syntax Diagnostic
When Python reports a syntax problem, inspect each part of the message:
- Filename: identifies the source file being read.
- Line number: shows the line where Python detected a problem.
- Code excerpt: displays the relevant source line.
- Caret indicator: points near the location where parsing failed.
- Error category: such as
SyntaxError,IndentationError, orTabError.
The caret is a starting point, not a guarantee that the exact character is the true cause. An unclosed quotation mark or parenthesis can cause Python to report a later line. Always inspect the marked line and the preceding line or lines.
File "example.py", line 2
if age >= 18
^
SyntaxError: expected ':'
In this example, the filename is example.py, the reported line is line 2, and the missing colon is indicated by the error category and message.
Common Beginner Syntax Mistakes
| Mistake | Why Python Rejects It | Typical Correction |
|---|---|---|
| Misspelled keyword | A reserved word must use its exact spelling. | Change whille to while. |
| Missing colon after a block header | A compound statement must end its header with :. | Write if age >= 18:. |
| Unclosed quote | Python cannot determine where the string ends. | Balance the opening and closing quotation marks. |
| Unmatched delimiter | Parentheses, brackets, and braces must be paired. | Match every ( with ), every [ with ], and every { with }. |
| Incorrect indentation | Leading whitespace defines blocks and must be consistent. | Indent the block consistently, preferably using four spaces. |
Missing Colons
A compound statement starts a block of indented code. Its header ends with a colon. Common examples include if, elif, else, while, for, def, class, try, and except.
age = 18
if age >= 18
print("Adult")
The if header is incomplete because it lacks a colon. The corrected version is:
age = 18
if age >= 18:
print("Adult")
Delimiters, Strings, and Expressions
Python requires balanced quotation marks and delimiters. These examples are malformed:
message = "Hello
numbers = [1, 2, 3
result = (4 + 5
Each line has an opening symbol without its matching closing symbol. Invalid punctuation or a malformed expression can cause the same kind of parsing failure.
Assignment and comparison also have different syntax and meanings. The single equals sign, =, assigns a value:
score = 10
The double equals operator, ==, compares values:
if score == 10:
print("Perfect score")
Writing if score = 10: is invalid syntax because an assignment cannot be used in that conditional position. Review assignment operators and comparison operators for the distinction.
Indentation
Indentation is leading whitespace used by Python to define code blocks. After a block header, the statements belonging to that block must be indented:
if temperature > 30:
print("It is hot")
Inconsistent indentation can produce an IndentationError or TabError. Do not mix tabs and spaces in the same block. A common beginner convention is four spaces per indentation level.
Running and Checking a Program
From a terminal, run a file with:
python error_example.py
Python parses the file and either displays a diagnostic or begins executing it. For quick experiments, start the interactive prompt:
python
The interactive prompt is useful for testing a small expression without running a complete file. The interactive Python prompt provides more practice.
Logical Errors
A logical error is a flaw in a program's reasoning, calculation, condition, variable update, or algorithm. Some introductory materials call this a semantic error, emphasizing that the meaning or intended outcome is wrong.
Code containing a logical error is syntactically valid and commonly runs without crashing. The difficult part is that Python may not display an error message. You must compare the program's behavior with its requirements and expected results.
For example, this program runs, but it calculates an average incorrectly:
first = float(input("First value: "))
second = float(input("Second value: "))
average = first + second / 2
print("Average:", average)
For inputs 3 and 4, the output is 5.0. The intended average is 3.5. Nothing in the expression violates Python grammar; the mistake is in the translated formula.
Operator Precedence and Grouping
Operator precedence is the set of rules that determines which operators Python evaluates first. Multiplication and division are evaluated before addition and subtraction unless parentheses change the grouping.
| Expression | Evaluation Order | Meaning |
|---|---|---|
a + b / 2 | Divide b by 2, then add a. | a + (b / 2), not the average of a and b. |
(a + b) / 2 | Add a and b, then divide the total by 2. | The average of two values. |
Parentheses are grouping symbols that override the default evaluation order. They also make the intended formula easier for another person to review. Correct the example with:
average = (first + second) / 2
With inputs 3 and 4, this produces 3.5. You can verify the result at the interactive prompt:
>>> (3 + 4) / 2
3.5
See Python arithmetic operators for related operators and calculations.
Finding and Correcting Logical Errors
- Restate the goal in plain language. For the average example: add both values, then divide the total by two.
- Choose known inputs. Use values whose correct result you can calculate by hand.
- Write the expected output. For 3 and 4, the expected average is 3.5.
- Inspect intermediate values. Print variables or use a debugger to see what the program is actually calculating.
- Review the logic. Check expressions, conditions, variable updates, loop boundaries, and operator choices.
- Make the smallest clear correction. Add grouping parentheses when the formula requires them.
- Retest broadly. Test normal, boundary, and unusual inputs after the correction.
Intermediate output can expose the incorrect order of operations:
first = 3
second = 4
half_second = second / 2
print("half_second =", half_second)
result = first + half_second
print("result =", result)
This prints half_second = 2.0 and result = 5.0. Those values reveal that only the second value was divided. Comparing intermediate values with the intended formula helps isolate the mistake.
Use Strong Test Cases
A calculation can look correct for particular inputs by coincidence. Test different positive, negative, zero, decimal, and equal-value inputs when those values make sense for the program. For conditions and loops, test values exactly at boundaries as well as just below and just above them.
Testing is especially important for logical errors because a successful run proves only that Python accepted and executed the code. It does not prove that the program fulfills its purpose.
Syntax Errors vs Logical Errors
| Characteristic | Syntax Error | Logical Error |
|---|---|---|
| Whether the program can run | Normally prevents normal execution of the affected source. | Usually allows the program to run. |
| When or how it is detected | Detected while the interpreter parses the source. | Detected by comparing behavior with requirements and expected results. |
| Typical symptom | A diagnostic such as SyntaxError, a missing colon message, or an indentation message. | Incorrect output, decision, calculation, state change, or loop behavior. |
| Examples | Misspelled keyword, missing colon, unmatched quote, or invalid indentation. | Wrong average formula, incorrect condition, wrong variable update, or incorrect loop boundary. |
| Main debugging approach | Read the filename, line, caret, error type, and nearby lines; fix grammar and punctuation. | State the intended behavior, calculate expected results, inspect intermediate values, and test cases. |
| Does a successful run prove correctness? | No. Correcting syntax only makes the code runnable. | No. Output must still be checked against the specification. |
Syntax Error Troubleshooting
If a SyntaxError identifies a loop or conditional, use this checklist:
- Read the error type and source line.
- Check the preceding line as well as the marked line.
- Verify that the keyword is spelled correctly.
- Look for a missing colon after the block header.
- Balance parentheses, brackets, braces, and quotation marks.
- Check indentation and avoid mixing tabs with spaces.
- Make one small correction, then run the file again.
If the marked location seems unrelated, look for an earlier unclosed string or delimiter. Python may not be able to identify the real cause until it reaches a later line.
Logical Error Troubleshooting
If a program runs but reports an incorrect average, choose simple inputs, calculate the expected result by hand, write the mathematical formula, and compare it with the Python expression. In this case, the required grouping is (first + second) / 2.
If a calculation looks plausible for some inputs but fails for others, the error may be masked by those particular values. Expand the test set, inspect intermediate values, and review operator precedence, conditions, and boundary handling.
Key Terms and Exam Notes
- Syntax error: Python grammar is violated, so the interpreter cannot parse the code correctly.
SyntaxError: the usual Python error type for source that cannot be parsed as valid Python.- Traceback: diagnostic output that identifies source locations and error information. Syntax diagnostics commonly include a filename, line number, excerpt, and caret.
- Keyword: a reserved word with a special meaning, such as
while,if,else, ordef. - Compound statement: a statement that starts a block and has a header ending in a colon.
- Logical error: valid code whose behavior does not match the intended algorithm or requirements.
- Expected output: the correct result predicted from a program's specification for a selected input.
The most important distinction is this: a syntax correction makes a program acceptable to the interpreter, while a logical correction makes its behavior match the intended goal. Both forms of checking are necessary.
For broader error categories, read about types of Python errors. Runtime problems are a separate category and are often handled with try and except statements.