To wrap up this first series of lessons, let’s review the three different kinds of errors that one might encounter in programming: Syntax Errors, Logic Errors, and Runtime Errors.
Syntax Errors
We know that the syntax of a language dictates how the keywords, operators, and punctuation must be used. A syntax error is simply one where the programmer has violated one of the syntax rules of the language. If a program has a syntax error, the Python interpreter will not execute it until the error is fixed. If you look in the Python shell window, the interpreter will give a detailed error message explaining what syntax error has occurred including the line number.
Common syntax errors include misspelling a keyword, passing the wrong number of arguments to a function, or mismatching quotation marks in a string.
1 2 3 |
print "Hello World!" # missing symbols, ( ) print("Hello World!') # mismatched quotation marks prant("Hello World!") # function name spelling error |
There are (unfortunately) hundreds of possibilities! The nice thing about the Mu is that if you pay attention to the automatic syntax highlighting and indenting you can often spot syntax errors right away.
Logic Errors
Logic errors occur when a program does not behave the way we intended. The Python Interpreter cannot catch these kinds of errors; only a sharp programmer can solve them. Common logic errors include forgetting the precedence (order of operations) of mathematical operators or designing a program with an infinite loop (a loop that never ends). Logic errors are often very subtle, and thus hard to catch.
Your share of the bill is $16
Instead of the more desirable and accurate:
Your share of the bill is $16.67.
To avoid logic errors in your code you need to be very systematic when testing. Don’t just try entering data that you know will work, try extreme values like negative numbers, 0, or very large positive numbers. Sometimes it helps to have someone else test your program as they might be more motivated to find problems. To isolate where a logic error is happening you should test each function in your program independently to ensure it behaves the way you want it to.
Runtime Errors
Runtime errors cause a program to stop executing (or “crash”). This is often the result of invalid user input to a program. There’s an old saying in computer science: “Garbage In – Garbage Out”. For example, the program below is syntactically perfect, but if a user enters their name (i.e., a string) instead of their age (i.e., an integer) the program will crash on line 2.
You Try!
-
- Add the heading “1-12 Types of Errors” to your learning journal and answer the following questions:
-
- Briefly explain the 3 different types of errors (in your own words!).
- In your opinion, which type of error is the easiest to deal with and why?
- In your opinion, which type of error is the most difficult to avoid and why?