Press enter to skip the top menu

Python Intermediate

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 in Python are a way of breaking up large programs into smaller, manageable chunks. This modular approach not only enhances the readability and maintainability of code but also facilitates reuse. By separating functionality into modules, developers can create libraries of functions that can be shared and reused across multiple programs. For instance, a module containing validation functions, as demonstrated in the uploaded file, can be used in any program requiring similar input validation.

Without modules, similar code might need to be replicated across different parts of a program or across multiple programs. By storing common functions like validateFloat or validateInt in a module, redundant code is eliminated.

Go to top

Revision

Multi choice

  • What is the main benefit of using modules in Python programming?
    • To make the code longer
    • To simplify error handling
    • To break up large programs into manageable chunks
    • To avoid the use of functions
  • What is a prerequisite for using the import keyword with a module?
    • The module must be named in all uppercase letters
    • The module filename must not contain spaces
    • The module must be located in the same directory as the Python interpreter
    • The module must include a .pyc extension
  • What does the validateFloat function do?
    • Validates if the input is an integer
    • Checks if a float value is within a specified range
    • Converts a float to an integer
    • Ensures input is a valid string
  • Why are spaces removed from module filenames?
    • To make them compatible with web servers
    • Because Python automatically strips spaces from filenames
    • Because the import keyword does not allow spaces
    • To increase the execution speed of the program
  • What Python feature allows multiple programs to use the same set of functions?
    • Functions
    • Lists
    • Modules
    • Classes
  • What keyword is used to include a module in a Python program?
    • include
    • use
    • import
    • define
  • In the validateInt function, what happens if the user enters a value outside the specified range?
    • The program terminates
    • A warning is displayed, and the user is prompted again
    • The value is automatically adjusted to fit the range
    • A default value is used
  • What is the purpose of the showData function in the payroll module?
    • To calculate gross, tax, and net
    • To validate input data
    • To display calculated results
    • To export data to a file
  • How are module functions accessed in a program that imports them?
    • By typing the function name directly
    • By using the file name followed by a dot and the function name
    • By redefining the functions in the main program
    • By using the load keyword
  • Which file stores the main body of the payroll program in the example provided?
    • C9_Validating_Module.py
    • C9_Payroll_Module.py
    • C9_Payroll_Main_Module.py
    • C9_Employee_Module.py

Fill the blanks

  • A module in Python is a way to ________ a large program into smaller, manageable chunks.
  • The keyword used to include a module in a Python program is ________.
  • Functions stored in a module are accessed using the ________ operator, which separates the module name and the function name.
  • Spaces in module filenames are replaced with ________ or CamelCase to ensure compatibility with the ________ keyword.
  • The function validateInt ensures that an integer input is within a ________ range.
  • In the payroll program, the main body of the program is stored in the file named ________.
  • The ________ function calculates the gross pay by multiplying hours worked by the rate per hour.
  • A key advantage of using modules is the ________ of code across multiple programs.
  • The calculateTax function applies a tax rate of ________% if the gross pay is less than $500.
  • When creating a module, the file extension must be ________.
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