Modules

Modules Summary Practice Exercise Assignment

Learning outcomes

On completion of this module you will know how to use modules to break up large programmes into more manageable chunks.

Download pdf version

Introduction

In the chapter on functions we looked at simplifying the layout of a programme by removing the complex calculation routines from the main programme and putting them into subroutines, or functions as Python prefers to call them.

This method definitely simplifies the main programme and makes it easier to read and interpret.  Similarly each function, when separated from its peers, is also much easier to understand.

The drawback of the creating of functions is that the programme, although more understandable, is now much longer than it was. Recall that Listing 3 of the chapter Functions, although the longest programme we have looked at so far, does not include the validation functions, which would have made it longer still.

In order to avoid very long programmes we can break them up into modules and store each module as a separate file.

Modules

Go to top

Our first module is shown in Listing 1.  It is almost identical to Listing 4 in the chapter on Functions.  The only difference is that it is stored in its own file: C9_Validating_Module.py

Up to now we have allowed spaces in our file names, however when we are dealing with modules we need to remove spaces and either replace them with underscores or else use CamelScript.  As you can see from line 1 of Listing 1 we are using underscored in our example. Later we will explain why we need to remove spaces from the filenames.

Listing 1

 1

#C9_Validating_Module.py

 2

 

 3

#function for validating a floating point number

 4

def validateFloat(base, top, prompt):

 5

    floatValue=float(input(prompt))

 6

    while (floatValue<float(base) or floatValue>float(top)):

 7

        print("Value must be in the range "+str(base) + " to " +str(top))

 8

        floatValue=float(input(prompt))

 9

    return floatValue

 10

 

 11

#function for validating an integer

 12

def validateInt(base, top, prompt):

 13

    intValue=int(input(prompt))

 14

    while (intValue<int(base) or intValue>int(top)):

 15

        print("Value must be in the range "+str(base) + " to " +str(top))

 16

        intValue=int(input(prompt))

 17

    return intValue

 

Listing 2 below contains the functions for calculating the payroll.  Again they are lifted directly out of Listing 3 of the chapter Functions.  The only difference is that they are stored in their own file – C9_Payroll_Module.py

Listing 2

 1

#C9_Payroll_Module.py

 2

      

 3

#function for calculating gross

 4

def calculateGross(hours, rate):

 5

    gross=hours*rate

 6

    return gross

 7

 

 8

#function for calculating tax

 9

def calculateTax(gross):

 10

    if gross<500:

 11

           tax=gross * 0.25

 12

    else:

 13

           tax=125 + (gross-500) * 0.33

 14

    return tax

 15

 

 16

#function for calculating superannuation

 17

def calculateSuper(gross,supercode):

 18

    if supercode == 0:

 19

        superAmt = 0

 20

    elif supercode == 1:

 21

        superAmt=gross*0.05

 22

    elif supercode == 2:

 23

        superAmt=gross*0.1

 24

    elif supercode == 3:

 25

        superAmt=gross*0.15

 26

    elif supercode == 4:

 27

        superAmt=gross * 0.2

 28

    else:

 29

        superAmt = -1

 30

    return superAmt

 31

 

 32

#function for calculating the net

 33

def calculateNet(gross, tax, super):

 34

    net=gross - tax - super

 35

    return net

 36

      

 37

#function for displaying results

 38

def showData(gross, tax, super, net):

 39

    print("Gross:    " + str(gross))

 40

    print("Tax:      " + str(tax))

 41

    print("Super:    " + str(super))

 42

    print("Net:      " + str(net))

 

Listing 3 below is again based on the main body of the programme from Listing 3 of the chapter Functions.  This, however, is where the greatest changes have occurred.  The first of those changes are in lines 4 and 5. Here we use the keyword import to import the two files C9_Validating_Module and C9_Payroll_Module.  Notice that when using the import keyword, we don’t need the file extension.  Also import does not allow spaces in filenames, hence the reason why we removed the spaces earlier.

Next we look at the input section.

Line 8 gets the validated data for the hours for us.  To validate the hours in our Functions chapter we used the function validateFloat().  We were able to call it directly there since the function and the main body of the programme were in the same file.  In our case the main body and the function are in different files and so when we call the function we must precede it with the name of the file. Hence line 8 calls the function as:

floatHours=C9_Validating_Module.validateFloat(……)

The same applies to lines 9 and 10.

In the processing section, all of the functions used for calculating the various parts of the payroll are stored in the file C9_Payroll_Module.  For this reason all of the names of the functions called in lines 13 – 19 have got C9_Payroll_Module in front of them.  In all cases the name of the file is separated from the name of the function by a full stop sign.

Listing 3

 1

#C9_Payroll_Main_Module.py

 2

 

 3

#Main body of programme

 4

import C9_Validating_Module

 5

import C9_Payroll_Module

 6

#input section

 7

strName = input("Enter employee's full name:  ")

 8

floatHours=C9_Validating_Module.validateFloat(5,60,"Enter value for hours:  ")

 9

floatRate=C9_Validating_Module.validateFloat(16,100,"Enter value for rate:  ")

 10

intSuperCode = C9_Validating_Module.validateInt(0, 4,"Enter value for super code:  ")

 11

 

12

#processing section

13

floatGross = C9_Payroll_Module.calculateGross(floatHours, floatRate)

14

floatTax = C9_Payroll_Module.calculateTax(floatGross)

15

floatSuper = C9_Payroll_Module.calculateSuper(floatGross,  intSuperCode)

16

floatNet = C9_Payroll_Module.calculateNet(floatGross,floatTax,floatSuper)

17

 

18

#output section

19

C9_Payroll_Module.showData(floatGross,floatTax,floatSuper,floatNet)

 

Summary

Go to top

Modules are a way of breaking up large programmes into manageable chunks. As well as making programmes more manageable another advantage of modules is that if more than one programme uses the same set of functions then, as long as those functions are stored in a separate module, all programmes that need use them can simply import that module.

Practice

Go to top

Copy the code from Listing 1, Listing 2 and Listing 3 into three separate files.  Ensure that you name the files according the comment on the first line of each listing.

Once all listings are copied into the files, try running the file containing code from Listing 3.

Exercise

Go to top

1.      What is the main purpose of Modules?

2.      When using modules what convention must we follow regarding file names?

3.      When a group of functions are removed from the main programme and stored in a separate file, what changes are mode to them?

4.      When the main body of a programme needs to call functions that are defined in a separate module what two alterations must be made to the code of that programme.?

Assignment Part 6

Go to top

Modify the Assignment Part 5 so that the functions in it are copied into a separate module. Next modify the main part of the programme so that it imports the module containing the functions.  Also ensure that the function calls within the main programme are preceded by the name of the file containing them.

Apart from its restructuring, the programme should run exactly as before.