成人快手

Writing error-free codeUsing comments

When writing programs, code should be as legible and error free as possible. Debugging helps keep code free of errors and documenting helps keep code clear enough to read.

Part of Computer ScienceProgramming

Using comments

A comment is one or more sentences that explain the purpose of a section of . A comment is placed just before (or after) the code to which it refers.

Well-written comments explain:

  • the name of the and its author
  • what the programmer intends the code to do
  • whether the programmer thinks the code could be better written
  • where the program may be incomplete or need updating

In , comments start with a hash symbol 鈥 鈥#鈥. Look at this simple Python program:

# Perimeter calculator
# Calculates the perimeter of a square
# By A.N.Other 2014

# Get length, store in variable length
length = int(input("Enter length"))

# Use length to calculate perimeter of square
perimeter = length * 4

# Output perimeter
print("Perimeter: ")
print(perimeter)

# Ideas for improvements:
# Message to user could be more explicit
# Could add a loop, letting the user choose to if they
# want to calculate another perimeter

This code has been fully commented.

Comments make your code easier to understand. Try to include meaningful comments in your code wherever possible.

Be aware, though, that including too many comments can actually make code HARDER to read - so use them appropriately.