Concepts / Testing Your Code

Testing Your Code

Syntax errors break Python's grammatical rules and prevent the program from running. Python reports them immediately with a line number and error message.

  • Programming

Three Ways a Program Can Fail

When a program does not work, the problem is not always the same kind of problem. A grammatical mistake can stop Python before the program runs. A sequencing mistake can let the program run while producing incomplete or out-of-order output. A mistake in a calculation, detail, or variable choice can also let the program run while producing the wrong result. These are syntax, logic, and semantic errors.

submitgrammar brokengrammar validsteps misorderedexecution completesgoal mismatchedInstructionsprogram writtenParsinggrammar checkedSyntax errorprogram stopsRunningstatements executeLogic errorwrong orderEvaluating resultgoal comparedSemantic errorwrong result
What happens during writing, parsing, running, and evaluating a Python program, and when does each error type appear?

The first debugging question is not simply “What went wrong?” Ask instead: Did Python reject the program's grammar, did valid statements happen in the wrong order, or did the valid calculation fail to match the intended goal?

Syntax Stops the Program

A syntax error breaks Python's grammatical rules. Python cannot parse the instruction, so the program does not run. Python reports the problem immediately with a line number and an error message. It may also show a caret pointing to where Python first realized that something was wrong.

parsegrammar mistakelocaterejectProgram textinstruction submittedGrammar checkPython parsesLine and messageproblem reportedCaretfirst recognized locationExecution stopsprogram does not run
How does Python detect a grammatical mistake, report its location, and prevent the rest of the program from executing?

In the source example, the name primt is used instead of print. Python cannot parse the line because it encounters an unknown token. The correct spelling is print. In another source example, I followed by a space and the word hate violates Python's grammar because Python expects an operator or the end of a statement, not a plain English phrase.

When Python reports a syntax error, begin at the reported line. Read the message, inspect the location marked by the caret when one is shown, and check the surrounding instruction for a grammatical mistake. Syntax errors are often quick to fix because Python identifies them before execution.

Valid Instructions, Wrong Order

A logic error occurs when the code is syntactically valid, but statements are in the wrong order or relate to one another incorrectly. Python can run the program because each instruction follows the grammar. The problem is that the sequence of valid instructions does not accomplish the intended process, so the output may be incomplete or out of order.

Finding an Incomplete Total

A program calculates a total, displays it, and then adds more items to the total. What kind of error is present, and where should you look?

Observe the execution: The program runs without a syntax error, so Python accepts the grammar of every instruction.

Trace the order: The total is displayed before the later items are added. The display instruction is valid, but it happens too early.

Compare with the goal: If the goal is to display the complete total, the statements do not occur in the order required by that goal.

Classify the problem: This is a logic error because the statements are valid but their order defeats the intended result.

Trace the program step by step and check whether each action occurs before the action that depends on it.

thenthenthenCalculate totalinitial itemsAdd itemsall itemsDisplay totalincomplete totalDisplay totalcomplete totalAdd itemslater items
How can valid instructions run successfully while producing an incomplete result because their order does not match the intended logic?

Correct Process, Wrong Meaning

A semantic error occurs when the code is syntactically perfect and logically ordered but does not achieve the intended goal. The program runs and produces output, yet the output is wrong because of a mistake in a calculation, detail, or variable choice.

  • Using the wrong variable name.
  • Applying the wrong formula.
  • Making an off-by-one calculation.

Semantic errors are difficult to detect automatically because the instructions can be grammatically valid and arranged in a sensible order. Python executes those instructions exactly as written. It does not know the goal you had in mind unless that goal is represented correctly in the program. Debugging therefore requires comparing the program's actual behavior with the intended goal.

Error typeRoot causeWhen it appearsObservable resultMain debugging action
SyntaxPython grammar is brokenBefore the program runsPython reports a line number and message; execution stopsRead the message and inspect the reported line and nearby text
LogicValid statements are in the wrong order or relate incorrectlyWhile the program runsThe program runs but output is incomplete or out of orderTrace the sequence of steps
SemanticA calculation, detail, or variable choice does not match the goalAfter valid execution produces a resultThe program runs but the output is wrongCompare actual behavior with intended behavior

A Debugging Trace

inspectsyntaxlogicsemanticrepair grammarrepair orderrepair meaningUnexpected behaviorprogram fails or surprisesClassify errorsyntax, logic, semanticPython feedbackline and messageTrace statementscheck order and detailsCompare with goalactual versus intendedCorrected programinstructions match goal
How do Python's reported location and the programmer's reasoning guide the move from a failing program to a corrected program?
  1. If Python reports a line number and message before execution, inspect the grammar around that location.
  2. If the program runs but output is incomplete or out of order, trace the statements in the order Python performs them.
  3. If the program runs and the sequence appears reasonable but the result is wrong, check calculations, variable choices, details, and off-by-one behavior.
  4. State the intended goal in precise terms.
  5. Compare the actual behavior with that goal and correct the instruction that creates the mismatch.

Practice the Classification

MEDIUM

For each situation, identify the error type and name the first debugging action you would take. Situation A: Python reports a line number and message before any output appears. Situation B: The program runs, but it displays a total before later items are added. Situation C: The program runs in a sensible order, but a variable choice produces the wrong result.

Hints
  • Use the phase of execution as your first clue.
  • A reported line and message before execution point toward a grammar problem.
  • An incomplete or out-of-order result points toward the sequence of statements.
  • A wrong result from an otherwise valid sequence points toward a calculation, detail, or variable choice.

What do you think happens?

A program runs without an error message, but its output does not match the programmer's goal. Can Python automatically determine the intended result from the program alone?

  • Yes, because Python can infer the programmer's intention
  • No, because Python executes the written instructions and the programmer must compare the result with the goal
Reveal answer

Answer: No, because Python executes the written instructions and the programmer must compare the result with the goal.

Logic and semantic errors can leave the program syntactically valid and able to run. Debugging requires tracing the behavior and comparing it with the intended goal.

Key Takeaways

  1. Syntax errors break Python's grammar, are reported before execution, and prevent the program from running.
  2. Logic errors involve valid instructions in the wrong order or with incorrect relationships, so the program runs but its output may be incomplete or out of order.
  3. Semantic errors occur when valid, logically ordered instructions fail to achieve the intended goal because of a calculation, detail, or variable-choice mistake.
  4. Python reports syntax problems, but it cannot automatically infer every logical or semantic intention.
  5. Effective debugging begins by classifying the error, then using Python's feedback, tracing, and comparison with the intended goal.

Key Takeaways

  • Syntax errors stop a program before it runs because Python cannot parse broken grammar.
  • Logic errors let a program run, but valid statements occur in an order that defeats the intended process.
  • Semantic errors let a program run and produce output, but the output is wrong because the instructions do not represent the intended goal.
  • Debugging becomes more efficient when you classify the error before deciding where to look.
  • Python follows written instructions exactly, so programmers must compare actual behavior with intended behavior.