Clarity through comments

Throughout this course, as well as developing your technical ability to program, we’ll also be modelling good practices and habits that we hope you’ll pick up.

One really important practice that we’ll be using throughout is the use of comments or annotations in our code to help communicate what the code is doing and how it’s working.

All programming languages support commenting in some form, and Python is no exception. In most text-based languages, there is a special character that is used to denote the start of a comment. In Python this is done with the # symbol. When it is used on a line, every following character on the same line is ignored by the computer, and can contain any text the programmer wants to insert. We might use comments in a number of different ways.

Some examples

  • We can use comments at the start of a program to describe its purpose:
# This program will display a welcome message and then find out the user's name

print("Welcome!")
name = input("What is your name?")

  • Comments can be added to the end of each line:
print("Welcome!")       #Displays a welcome message
name = input("What is your name?")     #Prompts the user for their name and stores it in a variable
  • A programmer might use comments to explain the purpose of different sections of code:
# Welcome the user
print("Welcome!")

# Collect their name, and greet them
name = input("What is your name?")
print("Hi {}".format(name))

#Collect the user's age
age = int(input("How old are you?"))

Multiline comments

Sometimes you may want to write longer comments over several lines. This is particularly useful when documenting your code. This can be achieved in a couple of ways:

  • Triple quoted strings can surround a piece of text over several lines, creating a multiline comment:
def someFuntion():

    '''
    The someFunction function does X, Y, Z
    First it does X
    then Y
    and finally Z
    '''
	
    print("done X")
    print("done Y")
    
	
  • The alternative is to precede each line with the # symbol:
def someFuntion():

    # The someFunction function does X, Y, Z
    # First it does X
    # then Y
    # and finally Z
    	
    print("done X")
    print("done Y")
    

Reflection

Use the comment section below to discuss the following questions:

  • How do comments benefit the author of the program?
  • How do the programmer’s comments benefit others?
  • How do you encourage your learners to include comments in their code?

Share this article:

This article is from the free online course:

Programming 102: Think Like a Computer Scientist

Raspberry Pi Foundation