



(15 ratings)
Different kinds of errors can occur in a program, and it is useful to distinguish among them in order to track them down more quickly:
Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.
Runtime errors are produced by the runtime system if something goes wrong while the program is running. Most runtime error messages include information about where the error occurred and what functions were executing. Example: An infinite recursion eventually causes a runtime error of "maximum recursion depth exceeded."
Semantic errors are problems with a program that compiles and runs but doesn't do the right thing. Example: An expression may not be evaluated in the order you expect, yielding an unexpected result.
The first step in debugging is to figure out which kind of error you are dealing with. Although the following sections are organized by error type, some techniques are applicable in more than one situation.
Syntax errors are usually easy to fix once you figure out what they are. Unfortunately, the error messages are often not helpful.The most common messages are SyntaxError: invalid syntax and SyntaxError: invalid token, neither of which is very informative.
On the other hand, the
message does tell you where in the program the problem occurred.
Actually, it tells you where Python noticed a problem, which is not
necessarily where the error is. Sometimes the error is prior to the
location of the error message, often on the preceding line.
If
you are building the program incrementally, you should have a good idea
about where the error is. It will be in the last line you added.
If you are copying code from a book, start by comparing your code to the book's code very carefully. Check every character. At the same time, remember that the book might be wrong, so if you see something that looks like a syntax error, it might be. Here are some ways to avoid the most common syntax errors:
1.Make sure you are not using a Python keyword for a variable name.
2.Check that you have a colon at the end of the header of every compound statement, including for, while, if, and def statements.
3.Check that indentation is consistent. You may indent with either spaces or tabs but it's best not to mix them. Each level should be nested the same amount.
4.Make sure that any strings in the code have matching quotation marks.
5.If you have multiline strings with triple quotes (single or double), make sure you have terminated the string properly. An unterminated string may cause an invalid token error at the end of your program, or it may treat the following part of the program as a string until it comes to the next string. In the second case, it might not produce an error message at all!
6.An unclosed bracket (, {, or [ makes Python continue with the next line as part of the current statement. Generally, an error occurs almost immediately in the next line.
7.Check for the classic = instead of == inside a conditional.
If
nothing works, move on to the next section.. can't get my program to
run no matter what I do.If the compiler says there is an error and you
don't see it, that might be because you and the compiler are not
looking at the same code. Check your programming environment to make
sure that the program you are editing is the one Python is trying to
run. If you are not sure, try putting an obvious and deliberate syntax
error at the beginning of the program. Now run (or import) it again. If
the compiler doesn't find the new error, there is probably something
wrong with the way your environment is set up.
If this happens, one approach is to start again with a new program like
"Hello, World!," and make sure you can get a known program to run. Then
gradually add the pieces of the new program to the working one.
Once your program is syntactically correct, Python can import it and at least start running it. What could possibly go wrong? My program does absolutely nothing.
This problem is most common when your file consists of functions and classes but does not actually invoke anything to start execution. This may be intentional if you only plan to import this module to supply classes and functions.
If it is not intentional, make sure that you are invoking a function to start execution, or execute one from the interactive prompt.
If a program stops and seems to be doing nothing, we say it is "hanging." Often that means that it is caught in an infinite loop or an infinite recursion.
If there is a particular loop that you suspect is the problem, add a print statement immediately before the loop that says "entering the loop" and another immediately after that says "exiting the loop." Run the program. If you get the first message and not the second, you've got an infinite loop. Most of the time, an infinite recursion will cause the program to run for a while and then produce a "RuntimeError: Maximum recursion depth exceeded" error. If that happens, go to the "Infinite Recursion" section below. If neither of those steps works, start testing other loops and other recursive functions and methods. If that doesn't work, then it is possible that you don't understand the flow of execution in your program.
If you think you have an infinite loop and you think you know what loop is causing the problem, add a print statement at the end of the loop that prints the values of the variables in the condition and the value of the condition.
For example:
while x > 0 and y < 0 :
# do something to x
# do something to y
print "x: ", x
print "y: ", y
print "condition: ", (x > 0 and y < 0)
Now when you run the program, you will see three lines of output for each time through the loop. The last time through theloop, the condition should be false. If the loop keeps going, you will be able to see the va lues of x and y, and you might figure out why they are not being updated correctly. Infinite Recursion
Most of the time, an infinite recursion will cause the program to run for a while and then produce a Maximum recursion depth exceedederror.
If you suspect that a
function or method is causing an infinite recursion, start by checking
to make sure that there is a base case. In other words, there should be
some condition that will cause the function or method to return without
making a recursive invocation. If not, then you need to rethink the
algorithm and identify a base case. If there is a base case but the
program doesn't seem to be reaching it, add a print statement at the
beginning of the functionor method that prints the parameters. Now when
you run the program, you will see a few lines of output every time the
function or method is invoked, and you will see the parameters. If the
parameters are not moving toward the base case, you will get some ideas
about why not.
Flow of Execution
If
you are not sure how the flow of execution is moving through your
program, add print statements to the beginning of each function with a
message like "entering function foo," where foo is the name of the
function Now when you run the program, it will print a trace of each
function as it is invoked.
When I run the program I get an exception.
If something goes wrong during runtime, Python prints a message that includes the name of the exception, the line of the program where the problem occurred, and a traceback.
The traceback identifies the function that is currently running, and then the function that invoked it, and then the function that invoked that, and so on. In other words, it traces the path of function invocations that got you to where you are. It also includes the line number in your file where each of these calls occurs.
The first step is to examine the place in the program where the error occurred and see if you can figure out what happened.These are some of the most common runtime errors:
You are trying to use a variable that doesn't exist in the current environment. Remember that local variables are local. You cannot refer to them from outside the function where they are defined.
TypeError
There are several possible causes:
You are trying to use a value improperly. Example: indexing a string, list, or tuple with something other than an integer. There is a mismatch between the items in a format string and the items passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for. You are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is self. Then look at the method invocation; make sure you are invoking the method on an object with the right type and providing the other arguments correctly.
You are trying to access an element of a dictionary using a key value that the dictionary does not contain.
You are trying to access an attribute or method that does not exist.
The index you are using to access a list, string, or tuple is greater than its length minus one. Immediately before the site of the error, add a print statement to display the value of the index and the length of the array. Is the array the right size? Is the index the right value?
20 Random Tutorials from the same category :
Whetting Your Appetite
Modules in Python
Simple Statements In Python
Schema evolution Python
Floating Point Arithmetic: Issues and Limitations
Control Structures In Python
Modules
Extending and embedding Python
GUI Applications in Python
Brief Tour of the Standard Library
Python with other Languages
Use serialization to store Python objects
Data Structures
History
Why is Python popular with Linux users?
An Informal Introduction to Python
Conditionals and recursion - Python
A peck of pickled Python
Python 101 -- Introduction to Python
The Other Scripting Language that Starts with "P"













