M&C5: Debugging functions and code

Programming is an art. There exists no recipe for writing code without bugs, but there are guidelines students can follow to write good code and code that can be debugged easier. Producing correct code is a challenge for every programmer.

With respect to functions, the first rule is to ensure that students understand the rules and conventions of writing and using functions.  Also encourage your students to continue the use of best practices learned earlier when other concepts were introduced.

Syntax errors, indentation errors, name errors (i.e., name not found) arising when writing functions are typically related to not following the general rules.  Hence, tell your students:

  • Learn the syntax and indentation rules. Python has few rules compared to other languages and learning them is a very good idea.
  • If you are not sure how to correct a syntax error, look up the rules. Or, execute the statement in an interpreter environment or PythonTutor.
  • Don’t copy code from Word processing files. Copying a single statement may be okay unless the statement contains quotes.
  • Make use of the fact that environments like Canopy will pop up a help window while you are typing (e.g., after typing range(  a window will tell you the rules of range and how to use it).
  • When writing a program, write it incrementally. Write small portions and make sure they contain no syntax errors.

Tell your students to not write all functions at once.  Even when they are sure they know how to do it!  Instead:

  • Write one function at a time, possibly breaking it into smaller pieces
  • Split complex expressions containing function calls into multiple statements
  • Get one function written and tested at a time
  • As other functions are added,  pay attention to possible interactions.

General debugging guidelines discussed in other blog entries should be used when run-time errors happen.

Remind your students: If code doesn’t work as expected, that does not mean they should write more code. Instead, they should return to a state where the code was working as expected.