Errors (or bugs) are accidental mistakes in the code.
They should not be confused with malware (deliberate attempts to bring down computer systems).
There are two types of errors.
Syntax errors occur when the code doesn't follow the rules (syntax) of the programming language.
Example 1 shows some Python code with a syntax error.
Example 1
print "Hello, World!"
This is a syntax error because there should be brackets around the string: the interpreter can't understand what the code is supposed to do.
Example 2 shows the output of Example 1.
Example 2
print "Hello, World!"
^^
SyntaxError: invalid syntax
Code with a syntax error will not be able to run.
Logic errors occur when the program does something unexpected.
Example 3 shows some Python code with a logic error.
Example 3
inp = input("Quit (y/n)? ")
if inp == "n":
print("Bye!")
quit()
else:
play()
The logic error here is in line 2, in the condition of the if
statement. The "n"
should be "y"
.
Example 4 shows the output of Example 3 when the input is "n"
.
Example 4
Quit (y/n)? n
Bye!
Code with a logic error can still run, but it won't do what you want it to do.
Which type of error is harder to track down?
Logic error - the compiler/interpreter will tell you exactly where a syntax error is, but it won't know if there is a logic error.