A program can fail in different ways. Sometimes Python cannot understand the code’s structure. Sometimes the code runs, but its result is not what we intended. These are different problems, and recognizing the difference helps us investigate.
When the code cannot be read as Python
Python has rules for how code must be written. Those rules are its syntax. A syntax error occurs when code breaks one of them.
print("Train arriving)
The text begins with a double quotation mark but never closes it. Python reports a SyntaxError rather than displaying the message. The exact wording and formatting of the error can vary with the Python version and the environment.
The corrected instruction closes the string before the parenthesis:
print("Train arriving")
When examining a syntax error, look at the location Python reports and the code immediately around it. The cause is not always on the precise character identified: an earlier missing quote or bracket can change how Python reads what follows.
When the result is wrong
Now consider a report that should show the total number of seats across two carriages, one with 24 seats and the other with 18:
print(24 - 18)
This is valid Python, and it displays 6. The problem is in the instruction: subtraction was used when the intended operation was addition. This is a logic error: the program runs, but its behavior does not match the intended result.
The corrected expression produces the total:
print(24 + 18)
42
Python can report that an instruction is invalid, but it cannot generally infer that we meant to add rather than subtract. We need an expected result to compare against the actual one.
A useful order for investigating
What did we expect?
↓
What did the program actually do?
↓
Did Python report an error?
↙ yes ↘ no
Read the message Compare the result
and nearby code with the intended steps
Start with a small example where the expected result is known. If an error message appears, read it and inspect the relevant code. If the program runs but the answer is wrong, trace the operations and check the values and their types. After a change, run the example again and compare the new result with the expectation.
Testing a program means checking its behavior against expectations; it is useful even when the program runs without errors. A correct result for one example is evidence for that case, not proof that every possible case works.
Performance is a separate concern: a correct program may still take more time or resources than appropriate. We can study that after we have a clearer understanding of what a program is meant to do and whether it does it correctly.