HybridE

Skills books › Coding for Beginners

How to find and fix bugs in a Python program

A bug is a mistake in a program. Start with the last line of the error message, which says what went wrong, and the line number just above it, which says where. When there is no message and the answer is simply wrong, check the program against a sum whose answer you already know.

Three kinds of error

How to read an error message

When an error happens inside a function, the message lists every line on the way there. The last few lines matter most.

  1. Read the last line. It names the kind of error and explains it.
  2. Look at the line number just above it.
  3. Ask what values the variables had on that line.
  4. Fix one thing, and run the program again.

You can also copy the last line of the message into a search engine. Leave out your own file and variable names.

Finding a logic error

The only way to catch a logic error is to check answers you already know.

In the book's example, a learner's program should give the average of four marks: 60, 70, 80 and 90. By hand, the total is 300 and the average is 75. The program says 100.

She adds a print check, an extra line that shows the total and the number of marks part of the way through. It shows a total of 300 and a count of 4. Both are right, so the mistake must come after that. She had divided by 3 instead of by the number of marks.

The bug sits between the last right value and the first wrong one. Print the values in the middle to find it.

Two other methods help:

Handling bad input with try and except

A run-time error does not have to stop the program. Python's try runs some code. If a named error happens, except runs instead.

A common use is asking for a number. If someone types "ten" instead of 10, the program can print a polite message and ask again, instead of crashing.

Test with a plan

Before you call a program finished, test it with three kinds of value:

The book's example plan for a data-cost program has just four tests: 200 MB, exactly 1 GB, zero, and the words "two hundred". Four planned tests find more bugs than forty random ones.

How to ask for help

Ask in a way that gets you a good answer:

Writing this down often solves the problem before you send it.

This guide is based on Chapter 10 of Coding for Beginners, which shows the full code for each of these examples.

This guide comes from the e-book Coding for Beginners: Your First Programs, Step by Step. R195 incl. VAT.

See the book

Get new free guides by email. We send an email when we publish new guides, and nothing else. You can unsubscribe at any time. Privacy policy.