Python language basics 25: commenting your code

Introduction

In the previous post we saw how to organise your code so that you can pass in an argument to your main method from the command line. We saw how the command line arguments were included in the “args” property of the “sys” object. Args is a string array so we could simply use square brackets to extract the player name argument in our number guessing game.

In this post we’ll look at a topic that’s usually not very dear to programmers: documentation.

Code documentation

You can document your code in a separate document, like MS Word, but here we mean documenting your code directly in the Python source file. You can write comments directly in your code and the Python compiler will simply ignore them.

The simplest form of commenting is a single-line comment using the “#” character:

def main(args):
    gamer = args[1]
    print("Welcome to the game", gamer, "!")
    # Ask the player for the lower and upper limits of the game
    lower_limit_input = get_integer_input('Lower limit: ')
    upper_limit_input = get_integer_input('Upper limit: ')
    # then start the game
    guess_counter = play_game(lower_limit_input, upper_limit_input)
    # write the final guess counter
    finish_game(guess_counter)

The rows starting with “#” won’t be interpreted by the Python compiler.

If you’d like to write multiple lines as comments then you can use triple-quotes as follows:

def main(args):
    gamer = args[1]
    print("Welcome to the game", gamer, "!")
    # Ask the player for the lower and upper limits of the game
    lower_limit_input = get_integer_input('Lower limit: ')
    upper_limit_input = get_integer_input('Upper limit: ')
    # then start the game
    guess_counter = play_game(lower_limit_input, upper_limit_input)
    # write the final guess counter
    """
    This is a multiline
    comment, all of it will be ignored by the
    Python compiler
    """
    finish_game(guess_counter)

However, the preferred way for multi-line comments in Python is to simply start each line with the “#” character:

# This is a multiline
# comment, all of it will be ignored by the
# Python compiler

The triple-quotes are rather reserved for a special purpose.

Docstrings

There’s a code documentation feature in Python called Docstrings. Docstrings are used to document the overall usage of a function or other elements in your code. DocStrings can come in various formats in Python. We’ll briefly look at how PyCharm can help you add this type of documentation.

If you place the cursor in a function name you’ll see a lightbulb icon:

PyCharm help link for functions

Click the downward pointing arrow and select “Insert documentation string stub”. It will add a function comment stub along with the parameters:

def finish_game(guess_counter):
    """

    :param guess_counter:
    """
    print('Congratulations. It took you ' + str(guess_counter) + ' guesses to guess the correct number.')

If there’s a return statement in the code then the return type comment stub is also added:

def get_integer_input(prompt_text):
    """

    :param prompt_text:
    :return:
    """
    user_input = input(prompt_text)
    return int(user_input)

You can add an overall comment first and then also document the purpose and usage of the parameters and the return value:

def evaluate_guess(guess, random_number):
    """
    This function evaluates the
    player's guess. It prints Too large or Too small
    depending on the comparison

    :param guess: the player's guess of type integer
    :param random_number: the original number that the player has to guess
    """
    if guess > random_number:
        print('Too large')
    else:
        print('Too small')

We’ll start discussing a core element in object-oriented languages in the next post, namely objects.

Read all Python-related posts on this blog here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: