UNIHIVE

Study Hub UNIPORT CSC 280

CSC 280 · Introduction to Computer Programming

Debugging, testing and good programming style

Finding and fixing errors, choosing test data, tracing with a table, comments and indentation, and what makes a program good.

Our notes

1 min read

Debugging

Debugging is finding and removing errors (bugs). Ways to do it:

  • Read the error message: it gives the line number and the kind of error (SyntaxError, NameError, ZeroDivisionError, IndexError, TypeError).
  • Print statements: print variables at key points to see where values go wrong.
  • Dry run / trace table: follow the program by hand, one row per step.
  • Debugger: run one line at a time and watch variables (Thonny, VS Code).
  • Rubber-duck: explain your code line by line to someone (or something); you often spot the fault yourself.

Trace table example

total = 0
for i in range(1, 5):
    if i % 2 == 0:
        total = total + i

ii % 2 == 0?total
1no0
2yes2
3no2
4yes6

Final total = 6 (the sum of even numbers up to 4).

Choosing test data

KindExample for "score 0-100, pass ≥ 40"
Normal55, 72
Boundary (edge)39, 40, 0, 100
Invalid (erroneous)-5, 150, "abc"

A program is not finished until it gives the right answers for all three kinds, and rejects bad input politely.

Validating input

while True:
    s = input("Score (0-100): ")
    if s.isdigit() and 0 <= int(s) <= 100:
        break
    print("Please type a whole number from 0 to 100.")

Handling run-time errors

try:
    x = 10 / int(input())
except ZeroDivisionError:
    print("You can't divide by zero.")

Good programming style

  • Meaningful names (total_units, not t).
  • Comments that explain why: # 5-point scale used at UNIPORT.
  • Consistent indentation (four spaces in Python).
  • Small functions, each doing one job.
  • No magic numbers: PASS_MARK = 40 at the top instead of 40 scattered through the code.
  • Documentation: what the program does, its inputs and outputs, how to run it.

Qualities of a good program

Correct, reliable (handles bad input), efficient (not wasteful of time or memory), readable, maintainable (easy to change), portable (runs on other machines) and user-friendly.

Exams usually ask: define debugging; kinds of errors with examples; draw a trace table and give the output; choose normal, boundary and invalid test data; qualities of a good program.

Common mistake: testing only with "nice" data. Most bugs live at the boundaries (0, 40, 100) and with wrong input.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 280 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.