Press enter to skip the top menu

Python Programming

Modules

NCEA Compatibility

Module 91896: Use advanced programming techniques to develop a computer program

Requirements: creating methods, functions, or procedures that use parameters and/or return values. Using additional non-core libraries. Checking input data for validity. Correctly handling expected, boundary and invalid cases

Go to top

Learning Outcomes

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

Go to top

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.

Go to top

Modules

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
                    
                        #CC8_Validating_Module.py
                        
                        #function for validating a floating point number
                        def validateFloat(base, top, prompt):
                            floatValue=float(input(prompt))
                            while (floatValue < float(base) or floatValue > float(top)):
                                print("Value must be in the range "+str(base) + " to " +str(top))
                                floatValue=float(input(prompt))
                            return floatValue
                        
                        #function for validating an integer
                        def validateInt(base, top, prompt):
                            intValue=int(input(prompt))
                            while (intValue < int(base) or intValue > int(top)):
                                print("Value must be in the range "+str(base) + " to " +str(top))
                                intValue=int(input(prompt))
                            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
                    
                        #CC9_Payroll_Module.py

                        #function for calculating gross
                        def calculateGross(hours, rate):
                            gross=hours*rate
                            return gross
                        
                        #function for calculating tax
                        def calculateTax(gross):
                            if gross < 500:
                        	    tax=gross * 0.25
                            else:
                        	    tax=125 + (gross-500) * 0.33
                            return tax
                        
                        #function for calculating the net
                        def calculateNet(gross, tax):
                            net=gross - tax
                            return net
                        	
                        #function for displaying results
                        def showData(gross, tax, net):
                            print("Gross:    " + str(gross))
                            print("Tax:      " + str(tax))
                            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 – 16 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
                    
                        #C9_Payroll_Main_Module.py
                        
                        #Main body of programme
                        import C9_Validating_Module
                        import C9_Payroll_Module
                        #input section
                        strName = input("Enter employee's full name:  ")
                        floatHours=C9_Validating_Module.validateFloat(5,60,"Enter value for hours:  ")
                        floatRate=C9_Validating_Module.validateFloat(16,100,"Enter value for rate:  ")
                        intSuperCode = C9_Validating_Module.validateInt(0, 4,"Enter value for super code:  ")
                        
                        #processing section
                        floatGross = C9_Payroll_Module.calculateGross(floatHours, floatRate)
                        floatTax = C9_Payroll_Module.calculateTax(floatGross)
                        floatSuper = C9_Payroll_Module.calculateSuper(floatGross,  intSuperCode)
                        floatNet = C9_Payroll_Module.calculateNet(floatGross,floatTax,floatSuper)
                        
                        #output section
                        C9_Payroll_Module.showData(floatGross,floatTax,floatSuper,floatNet)
                    
                    

Go to top

Practice

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.

Go to top

Summary

Modules

Modules are a way of breaking up large programmes into manageable chunks.

They allow more than one program touse the same set of functions

Go to top

Assignment

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.

Go to top