Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Coding Style

What will we cover?

Several new uses for comments, how to layout code using indentation to improve readability and an introduction to the use of modules for storing our programs.

Comments

I've already spoken about comments in the 'More Sequences' section. However there are more things we can do with comments and I'll enlarge on those here:

Version history information

It ius good practice to create a file header at the start of each file. This should provide details such as the creation daye, author, date, version and a general description of the contents. Often a log of changes. This block will appear as a comment:

#############################

#Module: Spam.py

#Author: A.J.Gauld

# Date: 1999/09/03

#Version: Draft 0.4

#Description: This module provides a Spam object which can be

#combined with any other type of Food object to create

#interesting meal combinations.

#

###############################

#Log:

#1999/09/01 AJG - File created

#1999/09/02 AJG - Fixed bug in pricing strategy

#1999/09/02 AJG - Did it right this time!

#1999/09/03 AJG - Added broiling method(cf Change Req #1234)

################################

import sys, string, food

...

Commenting out redundant code

This technique is often used to isolate a faulty section of code. For example, assume a program reads some data, processes it, prints the output and then saves the results back to the data file. If the results are not what we expect it would be useful to temporarily prevent the (erroneous)data being saved back to the file and thus corrupting it. We could simply delete the relevant code but a less radical approach is simply to convert the lines into comments like so:

data = readData(datafile) for item in data:

results.append(calculateResult(item))

printResults(results)

######################

#Comment out till bug in calculateResult fixed

#for item in results:

#dataFile.save(item)

######################

print 'Program terminated'

42