Clarity through comments
Throughout this course, as well as developing your technical ability to program, I will also be modelling good practices and habits that I hope you’ll pick up.
One really important practice that I’ll be using throughout is the use of comments or annotations in my 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. You might use comments in a number of different ways.
Some examples
You 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 someFunction():
# The someFunction function does X, Y, Z
# First it does X
# then Y
# and finally Z
print("done X")
print("done Y")
...