The importance of comments in Python

The Theory:

Comments in Python
Comments in python: make code easier to read and maintain

Comments are used to make code easier to read, understand, debug and improve.

In python, a comment starts with a hash #

Comments can go at the end of a line of code or can take up a whole line:

All of Line 1 is a comment that describes what the next line does

Line 4 has some code followed by a comment which describes what that line does

You should aim to be consistent in your commenting style. I prefer using whole line comments with a blank line above the comment so that the code is split up into paragraphs as shown below.

There are 5 reasons why it can be helpful to write comments in your code:

1: Comments can help you explain what code does

If you break your code up into paragraphs and add a comment above each paragraph explaining what that section of code does, it can help you when you come back to your code later. It can also help other programmers who might have to understand, debug or extend your code.

2: Comments can help break code up into sections

Some people like to follow a set pattern of organising their code by splitting their code into sections. If you’re studying Edexcel GCSE Computer Science, the code you’ll see in the practical exam will be split into paragraphs, each one labelled with comments as shown below:

This program will choose and display a random fruit. Notice how the code is split into sections for importing modules, constants, global variables and then the main program.

3: Comments can help you plan before you write any code

Sometimes starting writing a new program from a blank file can be quite a challenge. It can be really helpful to break down what you need your program to do and write down those steps as comments, before you write any other code.

The code below is an example of decomposing (breaking down) how to draw a robot by using comments:

4: Comments can give instructions to you or other programmers

I often write instructions for students as comments in code so that they know what they have to do if I share code with them. You can also write instructions to yourself to keep track of what you still need to do next time you see the code:

5: Comments can be used to give credit to people or websites that helped you write your code

The first line of the code below shows a comment with a link to the code I adapted slightly to draw a robot which I adapted slightly. Using comments like this allows you to avoid plagiarising other people’s ideas and work and lets you keep track of useful resources for future reference

Page 1: Intro

Page 2: The theory: learn what you need to know as fast as possible.

Page 3: Try it: try out and adapt some working python code snippets.

Page 4: Debug it: Learn how to find and fix common mistakes.

Page 5: Extend it: Choose a project idea to use your newfound python skills.

Leave a Reply