Page 244 - Computer Science V2.0 Class 11
P. 244

9                                                                    MODULES















                Chapter Outline


                9.1 Built-in Modules                               9.2 User-defined Functions Revisited
                9.3 User-defined Modules








              Introduction

              In  the  last  chapter  on  Python  Functions,  we  discussed  several  predefined  built-in  functions  such  as  input(),
              print(), int(), and abs(), dealing with input-output, data type conversion, and mathematical operations.
              We also learnt to develop user-defined functions to perform some simple, useful tasks. However, Python also provides
              specialised modules for specific tasks such as math  and statistics,  which provides several functions for
              mathematical and statistical computations. Similarly, the random  module provides several functions for random
              number generation. We will also develop some user-defined functions. Sometimes, a user may like to specify values
              of only the first few parameters because other parameters may take preassigned values. The preassigned values are
              called default values, and the corresponding parameters are called default parameters. Also, there may be situations
              where we need to specify only a few arguments, possibly in a sequence different from the list of formal parameters,
              we will study the use of keyword arguments.

              9.1 Built-in Modules

              A Python module is just a Python script. Python provides several modules, each of which contains several useful
              functions. Often, it is convenient to use predefined functions available in Python modules. However, to use these
              functions, we need to import the relevant module using the following syntax:
              import <modulename>
              Once a module is imported, we can use all the functions defined in the module by preceding function name by the
              name of the module and a dot(.) operator as shown below:

              <modulename>.<functionname>()
              For example, to use the sqrt() function defined in the math module, we first import the math module and then use
              sqrt() function to find the square root of 25, as follows:

               >>> import math
               >>> math.sqrt(25)
                    5
               230   Touchpad Computer Science (Ver. 2.0)-XI
   239   240   241   242   243   244   245   246   247   248   249