Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

19-Lambda Function, Modules, CSV Files, Numpy-18-01-2023

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

What is Modular Programming?

Modular programming is the practice of segmenting a single,


complicated coding task into multiple, simpler, easier-to-manage
sub-tasks. We call these subtasks modules. Therefore, we can build a
bigger program by assembling different modules that act like building
blocks.

Modularizing our code in a big application has a lot of benefits.

Simplification: A module often concentrates on one comparatively


small area of the overall problem instead of the full task. We will have a
more manageable design problem to think about if we are only
concentrating on one module. Program development is now simpler and
much less vulnerable to mistakes.

Flexibility: Modules are frequently used to establish conceptual


separations between various problem areas. It is less likely that changes
to one module would influence other portions of the program if modules
are constructed in a fashion that reduces interconnectedness. (We might
even be capable of editing a module despite being familiar with the
program beyond it.) It increases the likelihood that a group of numerous
developers will be able to collaborate on a big project.

Reusability: Functions created in a particular module may be readily


accessed by different sections of the assignment (through a suitably
established api). As a result, duplicate code is no longer necessary.

Scope: Modules often declare a distinct namespace to prevent identifier


clashes in various parts of a program.

In Python, modularization of the code is encouraged through the use of


functions, modules, and packages.
Python Modules
In python, module is a file that will contain a set of objects such as
functions, variables, classes, etc., to use in your applications.

Any file that contains a python code with a .py extension, we will call it a
module. For example, the samplemodule.py file is a module, and you can
use it in any python script by importing a module
with samplemodule name using an import statement.

In python, the modules are useful to reduce the code redundancy by


keeping the common functionalities such as functions, variables, etc., in
one place and use it in any interpreter session or python script.

Create a Module
In python, you can create a module by writing the following code in
the samplemodule.py file.

def add(x, y):


return x + y
def subtract(x, y):
return x - y
users = ["Suresh", "Rohini", "Trishika"]
If you observe the above code, we created a module (samplemodule) with
a combination of functions and variables.

Import Module
In python, you can import the module by using the import keyword. To use the
module (samplemodule) that we created in any python script or interpreter, you need
to use an import statement like as shown below.

import samplemodule
Following is the example of using the module ( samplemodule) that we created in
python script.

import samplemodule

a = samplemodule.add(10, 40)
b = samplemodule.subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
for user in samplemodule.users:
print(user)
If you observe the above code, we imported the module ( samplemodule) and
accessing the functions and variables.
The above python module example will return the result as shown below.

Sum: 50
Subtract: 50
Suresh
Rohini
Trishika
If the defined module is not found, it will throw the ModuleNotFoundError exception.

Search Module Path


In the above example, we are able to import the newly created modules
without specifying any module path because by default the python
interpreter will search in the following directory paths to locate the
modules.

 First, it will search the current working directory path for the specified
module.
 If not found, it will search the directories that are in
the PYTHONPATH environment variable.
 If still not found, it will search the default installation directory.

Whenever the interpreter starts, the sys module will get all the location
paths and keep them in the list like as shown below.

import sys

print(sys.path)
The above python module example will return the result as shown below.

['D:\\Python Examples', 'C:\\Program Files\\Python38\\Lib\\


idlelib', 'C:\\Program Files\\Python38\\python38.zip', 'C:\\
Program Files\\Python38\\DLLs', 'C:\\Program Files\\Python38\\
lib', 'C:\\Program Files\\Python38', 'C:\\Program Files\\
Python38\\lib\\site-packages']

Rename Imported Module


If you want, you can rename the imported module using as keyword.
The as keyword will help us to create an alias name for the imported
module.

Following is the example of renaming the imported module


using as keyword in python.
import samplemodule as sm

a = sm.add(10, 40)
b = sm.subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
for user in sm.users:
print(user)
In the above example, we created alias name (sm) for the imported
module (samplemodule) using as keyword and accessing the module
resources using the alias name.

The above python module example will return the result as shown below.

Sum: 50
Subtract: 50
Suresh
Rohini
Trishika

Import Specific Items from Module


When you import the module using an import statement, it will import all the module
resources. If you want to import only the specific objects of a module, you can
achieve it by using from keyword with the import statement.

When you use from keyword to import specific module resources, you don’t need to
use the module name to refer to the module elements.

Following is the example of importing specific objects from a module


using from keyword with the import statement.

from samplemodule import add

a = add(10, 40)
b = subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
In the above example, we imported only add function
from samplemodule using from and import keywords but, we are trying to access
both add and subtract functions.

The above python module example will return the result as shown below.

Traceback (most recent call last):


File "D:\pythonmodule.py", line 4, in <module>
b = subtract(100, 50)
NameError: name 'subtract' is not defined
Using from keyword, we imported only add function but, we tried to access
the subtract function also that’s why we got an exception.
Following is the example of importing multiple parts from the module using from…
import statement.

from samplemodule import add, subtract

a = add(10, 40)
b = subtract(100, 50)
print("Sum:", a)
print("Subtract:", b)
The above python module example will return the result as shown below.

Sum: 50
Subtract: 50

Use dir() Function


If you want to see the list of available function/variable names in the module, you
can use the built-in dir() function.

import samplemodule as sm

x = dir(sm)
print(x)
The above python module example will return the result as shown below.

['__builtins__', '__cached__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__', 'add',
'subtract', 'users']

Reload the Module


Generally, the python interpreter will load the module only once per session. After
loading, if you make any changes to the defined module, those will not reflect in the
current session until we close and restart the interpreter.

To get the latest module changes without closing the current interpreter session, you
need to use the reload() function from the imp module to reload the defined
modules.

import imp

imp.reload(samplemodule)

Built-in Modules
By default, python has provided a set of built-in modules such as math, os, sys, etc.,
to use in any python script file. The built-in modules will load automatically whenever
the interpreter starts, and these modules are available as a part of python libraries.

To know more about built-in modules, refer to built-in modules in python.

Python Built-in Modules


The module is a file that will contain a set of functions, variables, classes, etc., to use
in your applications.

Python has a set of built-in modules such as math, os, sys, etc., to use in any
python script file. The built-in modules will load automatically whenever
the interpreter starts, and these modules are available as a part of python libraries.

The built-in modules that are available in python interpreter written in C. To see the
list of all available built-in modules, execute the help('modules') command in the
python console as shown below.

>>> help('modules')
The above command will return all the available modules in the python interpreter.

__future__ _tkinter getpass sched


_abc _tracemalloc gettext
secrets
_ast _warnings glob
select
_asyncio _weakref gzip
selectors
_bisect _weakrefset hashlib
setuptools
_blake2 _winapi heapq
shelve
_bootlocale _xxsubinterpreters hmac shlex
_bz2 abc html
shutil
_codecs aifc http
signal
_codecs_cn antigravity idlelib site
_codecs_hk argparse imaplib smtpd
_codecs_iso2022 array imghdr
smtplib
_codecs_jp ast imp
sndhdr
_codecs_kr asynchat importlib
socket
_codecs_tw asyncio inspect
socketserver
_collections asyncore io
sqlite3
_collections_abc atexit ipaddress
sre_compile
_compat_pickle audioop itertools
sre_constants
_compression base64 json
sre_parse
_contextvars bdb keyword ssl
_csv binascii lib2to3 stat
_ctypes binhex linecache
statistics
_ctypes_test bisect locale
string
_datetime builtins logging
stringprep
_decimal bz2 lzma
struct
_dummy_thread cProfile mailbox
subprocess
_elementtree calendar mailcap sunau
_functools cgi marshal
symbol
_hashlib cgitb math
symtable
_heapq chunk mimetypes sys
_imp cmath mmap
sysconfig
_io cmd modulefinder
tabnanny
_json code msilib
tarfile
_locale codecs msvcrt
telnetlib
_lsprof codeop multiprocessing
tempfile
_lzma collections netrc test
_markupbase colorsys nntplib
textwrap
_md5 compileall nt this
_msi concurrent ntpath
threading
_multibytecodec configparser nturl2path time
_multiprocessing contextlib numbers
timeit
_opcode contextvars opcode
tkinter
_operator copy operator token
_osx_support copyreg optparse
tokenize
_overlapped crypt os trace
_pickle csv parser
traceback
_py_abc ctypes pathlib
tracemalloc
_pydecimal curses pdb tty
_pyio dataclasses pickle
turtle
_queue datetime pickletools
turtledemo
_random dbm pip types
_sha1 decimal pipes
typing
_sha256 difflib pkg_resources
unicodedata
_sha3 dis pkgutil
unittest
_sha512 distutils platform
urllib
_signal doctest plistlib uu
_sitebuiltins dummy_threading poplib uuid
_socket easy_install posixpath venv
_sqlite3 email pprint
warnings
_sre encodings profile wave
_ssl ensurepip pstats
weakref
_stat enum pty
webbrowser
_statistics errno py_compile
winreg
_string faulthandler pyclbr
winsound
_strptime filecmp pydoc
wsgiref
_struct fileinput pydoc_data
xdrlib
_symtable fnmatch pyexpat xml
_testbuffer formatter queue
xmlrpc
_testcapi fractions quopri
xxsubtype
_testconsole ftplib random
zipapp
_testimportmultiple functools re
zipfile
_testmultiphase gc reprlib
zipimport
_thread genericpath rlcompleter zlib
_threading_local getopt runpy

Get Help on Modules


To get the details about a particular built-in module, you can use the help() method.
For example, after importing the math module, you can call help(math) to get
the math module details in python.
Following is an example of getting the details about the math module in python.

>>> import math


>>> help(math)
It will return the detailed info about the math module like as shown below.

If the information is more than one page, it will display -- More -- as shown in the
image, if you want to see more info, press Enter.

You can also use the built-in dir() function to get the particular module's available
names and attributes.

>>> dir(math)
The above statement will return the result as shown below.
We will learn more about built-in modules in the next chapters

Python Math Module


In python, the math module is useful to perform mathematical related operations.
The math module has different functions (trigonometric, logarithmic, conversion,
etc.) and constants to perform various mathematical tasks.

Math Constants
The following table lists the constants available in the python math module.

Constant Description

math.pi It will return the pi value.

math.tau It will return the tau value.

math.e It will return the Euler's number.

math.inf It will return the floating-point positive infinity.

math.nan It will return the floating-point NaN value.

Following is the example of using the math module constants in python.


import math

# Print the value of E


print ("E val:", math.e)
# Print the positive infinity
print ("inf val:", math.inf)
# Print the negative infinity
print ("Neg inf val:", -math.inf)
# Print the value of nan
print ("nan val:", math.nan)
# Print the value of pi
print ("pi val:", math.pi)
# Print the value of tau
print ("tau val:", math.tau)
The above python math module constants example will return the result as shown
below.

E val: 2.718281828459045
inf val: inf
Neg inf val: -inf

Method Description

math.acos() It will return the arc cosine of a number.

math.acosh() It returns the inverse hyperbolic cosine of a number.

math.asin() This method will return the arc sine of number

math.asinh() It returns the inverse hyperbolic sine of number

math.atan() It returns the arc tangent of a number in radians

math.atan2() It returns the arc tangent of y/x in radians

math.atanh() It returns the inverse hyperbolic tangent of number

math.ceil() It will round a number up to the nearest integer

math.comb() It returns the number of ways to choose k items from n items without
Method Description

repetition and order

math.copysign() It returns a float with the magnitude (absolute value) of x but the sign of y.

math.cos() It will return the cosine of a number.

math.cosh() It will return the hyperbolic cosine of a number.

math.degrees() It converts angle x from radians to degrees.

math.dist() Returns the Euclidean distance between two points (p and q).

math.erf() It will return the error function of a number.

math.erfc() It will return the complementary error function of a number.

math.exp() It will return E raised to the power of x.

math.expm1() It returns exp(x) - 1

math.fabs() It will return the absolute value of the number.

math.factorial() It returns the factorial of a number.

math.floor() It will round the number down to the nearest integer.

math.fmod() It returns the remainder of x/y

math.frexp() It returns the mantissa and the exponent of a specified number.

math.fsum() It will return the sum of values in the iterable seq.


Method Description

math.gamma() It will return the gamma function at x

math.gcd() It will return the greatest common divisor of two integers

math.hypot() It will return the hypot value.

math.isclose() Determines whether two numbers are close in value or not

math.isfinite() Returns True, if the number is neither an infinite nor a NAN, otherwise
returns False.

math.isinf() Returns True, if the number is positive or negative infinity, otherwise returns
False.

math.isnan() Returns True, if the number is NaN (not a number), otherwise False.

math.isqrt() It rounds the square root number downwards to the nearest integer

math.ldexp() It will return the x * (2**i) of the given numbers x and i

math.lgamma() It will return the log gamma value of x

math.log() Returns the logarithm of a number or the logarithm of a number to base

math.log10() Returns the base 10 logarithm of x

math.log1p() Returns the natural logarithm of 1+x

math.log2() Returns the base 2 logarithm of x


Method Description

math.perm() Returns the number of ways to choose k items from n items without
repetition and with an order.

math.pow() Returns the value of x to the power of y

math.prod() Returns the product of all the elements in the input iterable.

math.radians() It converts a degree value into radians

math.remainder( It returns the closest value that can make the numerator completely divisible
) by the denominator

math.sin() It returns the sine of number

math.sinh() It returns the hyperbolic sine of number

math.sqrt() It will return the square root of number

math.tan() It returns the tangent of number

math.tanh() It returns the hyperbolic tangent of number

math.trunc() It returns the truncated integer parts of a number

nan val: nan


pi val: 3.141592653589793
tau val: 6.283185307179586

Math Functions
Same as constants, the math module has different methods to perform
mathematical operations.

Following is the example of using math module functions to perform different


operations in python.
import math

# Print the square root of number


print (math.sqrt(64))
# Rounds number up to nearest integer
print (math.ceil(5.647))
# Rounds number down to nearest integer
print (math.floor(5.647))
# Print the power of number
print (math.pow(5,3))
# Print the sine of a number
print (math.sin(60))
# Print the cosine of a number
print (math.cos(60))
# Print the tangent of a number
print (math.tan(60))
The above python math module example will return the result as shown below.

8.0
6
5
125.0
-0.3048106211022167
-0.9524129804151563
0.320040389379563
The following table lists the different methods available in the math module to
perform logarithmic, trigonometric, etc., operations based on our requirements.

Python Random Module


In python, we don’t have any specific functions like random() to generate random
values. If you want to generate some random values, you need to import a built-
in random module.

Following is the example of importing a built-in random module to generate the


random number.

import random

#generate random value


print(random.random())
If you observe the above example, we imported the random module using
the import keyword and used the random() method to generate a random number.
Whenever you execute the above python program, you will get a random value
between 0.0 to 1.0.

Like the random() method, the random module has different methods to generate
random numbers based on your requirements.
Randint() Method
If you want to generate the random integer values between the defined range of
values, you need to use randint() method.

Following is the example of importing a built-in random module to generate the


random number between 2 to 10 in python.

import random

#generate a random value between 2 to 10


print(random.randint(2, 10))
In randint() method, the two parameters (start, end) are required. Whenever you
execute the above python program, you will get a random value between 2 to 10.

Randrange() Method
Same as the randint() method, the randrange() method also will generate the
random value between the specified range, but it will accept three parameters
(start, stop, step).

The first parameter is to define the starting position and its optional. By default, it
will consider 0 as the starting position. The second parameter to define the stop
position and its required. The third parameter to specify the incrementation and its
optional. By default, it's 1.

Following is an example of using the randrange() function to generate the random


number based on python's defined range values.

import random

print(random.randint(2, 10))
print(random.randrange(2,20,5))
print(random.randrange(2,100,20))
The above random module program will generate the random numbers between the
defined range values using the randrange() method.

2
17
82

Seed() Method
If you want to generate the same random number when you execute the above
program, you need to use the seed(n) method in the random module. Here, the
value n should always be the same; if you want to change the random value, then
change the n value.

Following is an example of the random module to generate the same random


number in python.
import random

#Always generate the same random number


random.seed(5)
print(random.randint(2, 10))
The above program will always generate the same random number ( 6)
between 2 and 10 based on the seed value. If you want a different random value, you
can change the value of the seed() method.

Choice() Method
The random module choice() method is useful to return the randomly selected
element from the specified sequence. The given sequence must be non-empty.
Method Description

random() It returns the random number between 0.0 and 1.0.

randint() It generates a random number between the specified range.

randrange() It will generate a random number between the specified range.

seed() It will return the same random number.

shuffle() It will randomly reorder the items in the sequence.

choice() It will return random elements from the specified sequence.

choices() It will return a list with random elements from the specified
sequence.

sample() It will return a list with the defined number of random elements
from the sequence.

getstate() It will return the internal state of a random number generator.

setstate() It will restore the internal state of a random number generator.

getrandbits() It will return a number that represents the random bits.

uniform() It will return a random float number between two given numbers.

triangular() It will return a random float number between two given numbers,
you can also use a mode parameter to specify the midpoint
between the two numbers.

betavariate() It will return a random number between 0.0 and 1.0 based on the
beta distribution.

expovariate() It will return a random float number based on the exponential


distribution.

gammavariate() It will return a random float number based on the gamma


distribution.

gauss() It will return a random float number based on the gaussian


distribution.
Following is the example of using the random module choice() method to get the
randomly selected element from the given sequence in python.

import random

print(random.choice('Tutlane'))
print(random.choice([1, 3, 10, 40, 50, 60]))
print(random.choice((1, 3, 10, 40, 50, 60)))
The above random module example will return the result as shown below.

n
40
1
The following table lists the different methods available in the random module to
randomly generate the numbers, randomly pick the elements, etc., based on our
requirements.

Python Statistics Module


In python, the statistics module has different functions to perform the mathematical
statistics of numeric data.

Following is the example of importing a built-in statistics module to calculate the


mathematical statistics of numeric data.

import statistics

print(statistics.mean([10, 15, 20, 25, 30]))


print(statistics.mean([4, 5, 6, 7, 8, 9, 10, 11]))
If you observe the above example, we imported statistics module
using import keyword and used mean() method to calculate the arithmetic mean
(average) of the numbers in the list.

The above statistics module example will return the result as shown below.

20
7.5
Like the mean() method, the statistics module has different methods to calculate
mathematical statistics of numeric data.

Median() Method
The statistics module median() method is useful to calculate the median (middle)
value of the numeric data in the list.

Following is the example of using the statistics module median() method in python.
import statistics

print(statistics.median([10, 15, 20, 25, 30]))


print(statistics.median([4, 5, 6, 7, 8, 9, 10, 11]))
The above statistics module median() method example will return the middle value
of numeric data in the list as shown below.

20
7.5

Mode() Method
The statistics module mode() method is useful to return the most common data
point on the list.

Following is an example of using the mode() function to get the common data point
from the python list.

import statistics

print(statistics.mode([10, 15, 10, 25, 30]))


print(statistics.mode([4, 5, 5, 7, 7, 9, 10, 11]))
print(statistics.mode(['tut', 'lane', 'tut', 'tutlane']))
The above statistics module mode() function example will return the most common
data points from the list as shown below.

10
5
tut

Stdev() Method
The statistics module stdev() method is useful to calculate the standard deviation of
the given data.

Following is an example of the statistics module stdev() method to calculate


python's sample data's standard deviation.

import statistics

print(statistics.stdev([10, 15, 10, 25, 30]))


print(statistics.stdev([4, 5, 5, 7, 7, 9, 10, 11]))
The above statistics module example will return the result as shown below.

9.082951062292475
2.5495097567963922

Variance() Method
The statistics module variance() method is useful to calculate the variance from a
given sample data.

Following is an example of the statistics module variance() method to calculate the


variance from python's sample data.

import statistics

print(statistics.variance([10, 15, 10, 25, 30]))


print(statistics.variance([4, 5, 5, 7, 7, 9, 10, 11]))
The above statistics module example will return the result as shown below.

82.5
6.5
The following table lists the different statistics module methods to calculate the
mathematical statistics of numeric data based on our requirements.

Method Description

mean() It will calculate the arithmetic mean (average) of the


numbers in the list.

harmonic_mean() It will calculate the harmonic mean (central location) of


the numbers in the list.

median() It will calculate the median (middle) value of the numeric


data in the list.

median_high() It will calculate the high median value of the numeric data
in the list.

median_low() It will calculate the low median value of the numeric data
in the list.

median_grouped() It will calculate the median of grouped continuous numeric


data in the list.

mode() It will return the most common data point in the list.

stdev() It will calculate the standard deviation of the given data.


Method Description

pstdev() It will calculate the standard deviation from an entire


population.

variance() It will calculate the variance from a given sample data.

pvariance() It will calculate the variance of an entire population.

Python Packages
Modules are the files that will contain the python statements, classes, functions, etc.
A package is a combination of one or more module files in a single directory.

Using packages, you can manage a large number of python files in different folders
and subfolders based on your requirements.

In python, if you create a directory with python files and an empty __init__.py file
will be treated as a package. To consider any directory as a package, that directory
must contain the __init__.py file. By default, the file __init__.py is empty, but you
can write your package initialization code based on your requirements.

Following is the pictorial representation of creating the package in python.

Create Package in Python


To create a package, first you need to create the directory, and the directory name
will be the name of the package. Here, our package name is “Sample_Package”
and add your module files inside the directory along with the __init__.py file to
consider it as a package in python.

The __init__.py file can be empty, or it can contain some valid python code. The
code whatever you write in the __init__.py file will execute whenever the package is
imported. So, it's better to write your package initialization code, e.g., import other
modules or set some values. Here, we added abc.py and xyz.py modules files inside
the directory with the following code.

abc.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

xyz.py
def multiply(a, b):
return a * b

def division(a, b):


return a/b

Import Modules from Package


In python, to access the modules from packages, you need to import the modules
along with packages.

Following is the sample way of accessing the modules from packages in python.

from Sample_Package import abc, xyz


or
import Sample_Package.abc
import Sample_Package.xyz
Create the pythonpackages.py file in the same package's directory location and
write the following code to access the modules from python packages.

from Sample_Package import abc, xyz

print("Addition:", abc.add(10, 20))


print("Subtract:", abc.subtract(20, 10))
print("Multiply:", xyz.multiply(10, 20))
print("Division:", xyz.division(100, 20))
If you observe the above packages example, we imported both modules (abc, xyz)
from the package (Sample_Package) and access the functions from each module.
When you execute the above python packages example, it will return the result as
shown below.

Addition: 30
Subtract: 10
Multiply: 200
Division: 5.0
Following is another way to access the modules from packages in python.

import Sample_Package.abc
import Sample_Package.xyz

print("Addition:", Sample_Package.abc.add(10, 20))


print("Subtract:", Sample_Package.abc.subtract(20, 10))
print("Multiply:", Sample_Package.xyz.multiply(10, 20))
print("Division:", Sample_Package.xyz.division(100, 20))

Import Specific Functions from Package


If you want, you can import only the specific functions from packages in python as
shown below.

from Sample_Package.abc import add


from Sample_Package.xyz import multiply

print("Addition:", add(10, 20))


print("Multiply:", multiply(10, 20))
The above python packages example will return the result as shown below.

Addition: 30
Multiply: 200
As discussed, every package will contain an empty __init__.py file. If required, you
can write your package initialization code in the __init__.py file to execute while
importing the package.

We will write a code in the __init__.py file to import the functions directly from the
packages instead of modules. Open your __init__.py file and write the code as
shown below.

__init__.py
from .abc import add
from .xyz import multiply
To test, create the testpkg.py file in the same directory where package
(Sample_Package) is located and write the code as shown below.
from Sample_Package import add, multiply

print("Addition:", add(10, 20))


print("Multiply:", multiply(10, 20))
If you observe the above code, we imported the functions directly from the package
instead of modules.

The above python packages example will return the result as shown below.

Addition: 30
Multiply: 200

Create Sub-packages Inside Package


If required, you can also create the sub-packages inside the python package as
following based on your requirements.

The sub-package module functions can be accessed as shown below.

from School.Class1.sub3 import marks


or
import Sample_Package.Class2.sub2
This is how you can use the python packages to maintain a large number of python
files in different folders and subfolders based on your requirements.
import math
x=5
y = 15
z=8
# returning the factorial
print ("The factorial of 5 is : ", math.factorial(x))
print ("The factorial of 15 is : ", math.factorial(y))
print ("The factorial of 8 is : ", math.factorial(z))

Python Modules List

Using Python built-in function help(), we can obtain the list


of built-in modules available in Python. On executing the
line help ('modules') in Python IDE, you can see all the
Python built-in modules. Some of the frequently used ones
are discussed below.

Module Description

Operato This module provides a set of pre-defined functions


r corresponding to operators in Python.
This module is used to print the complete decimal value
decimal when one number is divided by another number.

This module is used to generate random numbers.


Some of the pre-defined functions of this module are randint(), choice(),
random
uniform, etc.

string module provides a set of functions that are used to perform certain
operations on characters.
string
This module has pre-defined functions like capwords, ascii_letters, etc.

Math module is used to perform mathematical operations.


This module provides some pre-defined mathematical functions like sqrt,
math
factorial, etc.

Python Built-In Modules Examples

a) Example Using Operator Module

from operator import *


a, b = 10, 20#prints the product of the values 'a' and 'b'
print(mul(a, b))
#prints True if the value of 'a' is greater than 'b'. Else, False
print(gt(a, b))
#prints the remainder value, when the value of 'a' is divided by 'b'
print(mod(a, b))
#concatenates and prints the given two strings
print(concat("FACE", "Prep"))

Output:
200False10
FACEPrep

b) Example Using Decimal Module

from decimal import *


a, b = 10, 3
c=a/b
print(c)
print(Decimal(c)) #prints the complete decimal value of c

Output:
3.3333333333333335
3.333333333333333481363069950020872056484222412109375

c) Example Using Random Module

from random import *


print(randint(10, 20)) #prints a random number between the given range
list1 = [30, 23, 45, 16, 89, 56]
print(choice(list1)) #prints a random element from the given iterator
print(uniform(10, 20)) #prints a random float number between two given values

Output:
18
16
12.908184799437432

d) Example Using String Module

from string import *


print(capwords("fACE prep")) #capitalizes the first letter of each words
print(ascii_letters) #prints all lowercase and uppercase letters

Output:
FACE Prep
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

Python - Built-In Modules


In programming terminology, function is a separate, complete and reusable software

component. Long and complex logic in a program is broken into smaller,

independent and reusable blocks of instructions usually called a module, a

subroutine or function. It is designed to perform a specific task that is a part of entire

process. This approach towards software development is called modular

programming.

Such a program has a main routine through which smaller independent modules

(functions) are called upon. Each When called, a function performs a specified task
and returns the control back to the calling routine, optionally along with result of its

process.

Python interpreter has a number of built-in functions. They are always available for

use in every interpreter session. Many of them have been discussed in previously.

For example print() and input() for I/O, number conversion functions (int(), float(),

complex()), data type conversions (list(), tuple(), set()) etc. Here is complete list of

Python's built-in functions:

Built-in Functions

abs() delattr() hash() memoryview() set()

all() dict() help() min() setattr()

any() dir() hex() next() slice()

ascii() divmod() id() object() sorted()

bin() enumerate() input() oct() staticme

bool() eval() int() open() str()

breakpoint() exec() isinstance() ord() sum()


Built-in Functions

bytearray() filter() issubclass() pow() super()

bytes() float() iter() print() tuple()

callable() format() len() property() type()

chr() frozenset() list() range() vars()

classmethod() getattr() locals() repr() zip()

compile() globals() map() reversed() __impor

complex() hasattr() max()

Other functions will come up in later chapters of this tutorial.

In addition to built-in functions, a large number of pre-defined functions are also

available as a part of libraries bundled with Python distributions. However they are

not available for use automatically. These functions are defined in modules. A

module is a file containing definition of functions, classes, variables, constants or any

other Python object. Standard distribution of Python contains a large number of

modules, generally known as built-in modules. Each built-in module contains


resources for certain specific functionalities such as OS management, disk IO,

networking, database connectivity etc.

Most of the times, built-in modules are written in C and integrated with Python

interpreter.

A built-in module may be a Python script (with .py extension) containing useful

utilities.

To display list of all available modules, use following command in Python console:

>>> help('modules')

Resources from other modules are loaded by import statement. The general format

of using a function in any module is like this:

import module

module.function([arguments if any])

The sqrt() function in math module returns square root of a number.

>>> import math

>>> math.sqrt(100)

10.0

Some of the frequently used functions from certain built-in modules.

 os module

 random module

 math module

 time module

 sys module

 collections module

 statistics module
os module

This module has functions to perform many tasks of operating system.

mkdir():

We can create a new directory using mkdir() function from os module.

>>> import os

>>> os.mkdir("d:\\tempdir")

A new directory corresponding to path in string argument in the function will be

created. If we open D drive in Windows explorer we should notice tempdir folder

created.

chdir():

To change current working directory to use chdir() function.

>>> import os

>>> os.chdir("d:\\temp")

getcwd():

This function in returns name off current working directory.

>>> os.getcwd()

'd:\\temp'

Directory paths can also be relative. If current directory is set to D drive and then to

temp without mentioning preceding path, then also current working directory will be

changed to d:\temp

>>> os.chdir("d:\\")

>>> os.getcwd()

'd:\\'
>>> os.chdir("temp")

>>> os.getcwd()

'd:\\temp'

In order to set current directory to parent directory use ".." as the argument to

chdir() function.

>>> os.chdir("d:\\temp")

>>> os.getcwd()

'd:\\temp'

>>> os.chdir("..")

>>> os.getcwd()

'd:\\'

rmdir():

The rmdir() function in os module removes a specified directory either with absolute

or relative path. However it should not be the current working directory and it should

be empty.

>>> os.chdir("tempdir")

>>> os.getcwd()

'd:\\tempdir'

>>> os.rmdir("d:\\temp")

PermissionError: [WinError 32] The process cannot access the


file because it is being used by another process: 'd:\\temp'

>>> os.chdir("..")

>>> os.rmdir("temp")
listdir():

The os module has listdir() function which returns list of all files in specified

directory.

>>> os.listdir("c:\\Users")

['acer', 'All Users', 'Default', 'Default User',


'desktop.ini', 'Public']

random module

Python’s standard library contains random module which defines various functions

for handling randomization. Python uses a pseudo-random generator based upon

Mersenne Twister algorithm that produces 53-bit precision floats. Functions in this

module depend on pseudo-random number generator function random() which

generates a random float number between 0.0 and 1.0.

random.random(): Returns a random float number between 0.0 to 1.0. The

function doesn’t need any arguments

>>> import random

>>> random.random()

0.755173688207591

Other functions in random module are described here:

random.randint(): Returns a random integer between the specified integers

>>> import random

>>> random.randint(1,100)

58

>>> random.randint(1,100)

91
random.randrange(): Returns a random element from the range created by start,

stop and step arguments. The start , stop and step parameters behave similar to

range() function.

>>> random.randrange(1,10)

>>> random.randrange(1,10,2)

>>> random.randrange(0,101,10)

40

random.choice(): Returns a randomly selected element from a sequence object

such as string, list or tuple. An empty sequence as argument raises IndexError

>>> import random

>>> random.choice('computer')

'o'

>>> random.choice([12,23,45,67,65,43])

65

>>> random.choice((12,23,45,67,65,43))

23

random.shuffle(): This functions randomly reorders elements in a list.

>>> numbers=[12,23,45,67,65,43]

>>> random.shuffle(numbers)

>>> numbers

[23, 12, 43, 65, 67, 45]


>>> random.shuffle(numbers)

>>> numbers

[23, 43, 65, 45, 12, 67]

math module

This module presents commonly required mathematical functions.

 trigonometric functions

 representation functions

 logarithmic functions

 angle conversion functions

In addition, two mathematical constants are also defined in this module.

Pie π which is defined as ratio of circumference to diameter of a circle and its value

is 3.141592653589793, is available in math module.

>>> import math

>>> math.pi

3.141592653589793

Another mathematical constant in this module is e. It is called Euler’s number and is

a base of natural logarithm. Its value is 2.718281828459045

>>> math.e

2.718281828459045

This module contains functions for calculating various trigonometric ratios for a

given angle. The functions (sin, cos, tan etc.) need angle in radians as argument. We

on the other hand are used to express angle in degrees. The math module presents

two angle conversion functions (degrees() and radians()) to convert angle in degrees

to radians and vice versa.


Trigonometric functions:

radians(): converts angle in degrees to radians.(Note: π radians is equivalent to 180

degrees)

>>> math.radians(30)

0.5235987755982988

degrees(): converts angle in radians to degree.

>>> math.degrees(math.pi/6)

29.999999999999996

Following statements show sin, cos and tan ratios for angle of 30 degrees

(0.5235987755982988 radians)

>> math.sin(0.5235987755982988)

0.49999999999999994

>>> math.cos(0.5235987755982988)

0.8660254037844387

>>> math.tan(0.5235987755982988)

0.5773502691896257

sin(30)
0.499999999999999
0.5
94

0.866025403784438
cos(30) 3/2
7)
0.
tan(30) 1/2
5773502691896257

math.log(): returns natural logarithm of given number. Natural logarithm is

calculated to the base e.

math.log10(): returns base-10 logarithm or standard logarithm of given number.

>>> math.log10(10)

1.0

math.exp(): returns a float number after raising e (math.e) to given number. exp(x)

is equivalent to e**x

>>> math.log10(10)

1.0

>>> math.e**10

22026.465794806703

math.pow(): This function receives two float arguments, raises first to second and

returns the result. pow(4,4) is equivalent to 4**4

>>> math.pow(4,4)

256.0

>>> 4**4

256

math.sqrt(): This function computes square root of given number

>>> math.sqrt(100)

10.0
>>> math.sqrt(3)

1.7320508075688772

Representation functions:

The ceil() function approximates given number to smallest integer greater than or

equal to given floating point number. The floor() function returns a largest integer

less than or equal to given number

>>> math.ceil(4.5867)

>>> math.floor(4.5687)

sys module

This module provides functions and variables used to manipulate different parts of

the Python runtime environment.

sys.argv

This return list of command line arguments passed to a Python script. Item at 0th

index of this list is always the name of the script. Rest of the arguments are stored at

subsequent indices.

Here is a Python script (test.py) consuming two arguments from command line.

import sys

print ("My name is {}. I am {} years old".format(sys.argv[1],


sys.argv[2]))

This script is executed from command line as follows:

C:\python37>python tmp.py Anil 23

My name is Anil. I am 23 years old


sys.exit

This causes program to end and return to either Python console or command

prompt. It is used to safely exit from program in case of exception.

sys.maxsize

It returns the largest integer a variable can take.

>>> import sys

>>> sys.maxsize

9223372036854775807

sys.path

This is an environment variable that returns search path for all Python modules.

>>> sys.path

['', 'C:\\python37\\Lib\\idlelib', 'C:\\python37\\


python36.zip', 'C:\\python37\\DLLs', 'C:\\python37\\lib',
'C:\\python37', 'C:\\Users\\acer\\AppData\\Roaming\\Python\\
Python37\\site-packages', 'C:\\python37\\lib\\site-packages']

sys.stdin, sys.stdout, sys.stderr

These are file objects used by the interpreter for standard input, output and errors.

stdin is used for all interactive input (Python shell). stdout is used for the output of

print() and of input(). The interpreter’s prompts and error messages go to stderr.

sys.version

This attribute displays a string containing version number of current Python

interpreter.
collections module

This module provides alternatives to built-in container data types such as list, tuple

and dict.

namedtuple() function

This function is a factory function that returns object of a tuple subclass with named

fields. Any valid Python identifier may be used for a field name except for names

starting with an underscore.

collections.namedtuple(typename, field-list)

The typename parameter is the subclass of tuple. Its object has attributes mentioned

in field list. These field attributes can be accessed by lookup as well as by its index.

Following statement declares a employee namedtuple having name, age and salary

as fields

>>> import collections

>>> employee=collections.namedtuple('employee', [name, age,


salary])

To create a new object of this namedtuple

>>> e1=employee("Ravi", 251, 20000)

Values of the field can be accessible by attribute lookup

>>> e1.name

'Ravi'

Or by index

>>> e1[0]
'Ravi'

OrderedDict() function

Ordered dictionary is similar to a normal dictionary. However, normal dictionary the

order of insertion of keys in it whereas ordered dictionary object remembers the

same. The key-value pairs in normal dictionary object appear in arbitrary order.

>>> d1={}

>>> d1['A']=20

>>> d1['B']=30

>>> d1['C']=40

>>> d1['D']=50

We then traverse the dictionary by a for loop,

>>> for k,v in d1.items():

print (k,v)

A 20

B 30

D 50

C 40

But in case of OrderedDict object:

>>> import collections

>>> d2=collections.OrderedDict()

>>> d2['A']=20

>>> d2['B']=30
>>> d2['C']=40

>>> d2['D']=50

Key-value pairs will appear in the order of their insertion.

>>> for k,v in d2.items():

print (k,v)

A 20

B 30

C 40

D 50

deque() function

A deque object supports append and pop operation from both ends of a list. It is

more memory efficient than a normal list object because in a normal list, removing

one of iem causes all items to its right to be shifted towards left. Hence it is very

slow.

>>> q=collections.deque([10,20,30,40])

>>> q.appendleft(110)

>>> q

deque([110, 10, 20, 30, 40])

>>> q.append(41)

>>> q

deque([0, 10, 20, 30, 40, 41])

>>> q.pop()

40
>>> q

deque([0, 10, 20, 30, 40])

>>> q.popleft()

110

>>> q

deque([10, 20, 30, 40])

statistics module

This module provides following statistical functions :

mean() : calculate arithmetic mean of numbers in a list

>>> import statistics

>>> statistics.mean([2,5,6,9])

5.5

median() : returns middle value of numeric data in a list. For odd items in list, it

returns value at (n+1)/2 position. For even values, average of values at n/2 and

(n/2)+1 positions is returned.

>>> import statistics

>>> statistics.median([1,2,3,8,9])

>>> statistics.median([1,2,3,7,8,9])

5.0

mode(): returns most repeated data point in the list.

>>> import statistics


>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6])

stdev() : calculates standard deviation on given sample in the form of list.

>>> import statistics

>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])

1.3693063937629153

time module

This module has many time related functions.

time():

This function returns current system time in ticks. The ticks is number of seconds

elapsed after epoch time i.e. 12.00 am, January 1, 1970.

>>> time.time()

1544348359.1183174

localtime():

This function translates time in ticks in a time tuple notation.

>>> tk=time.time()

>>> time.localtime(tk)

time.struct_time(tm_year=2018, tm_mon=12, tm_mday=9,


tm_hour=15, tm_min=11, tm_sec=25, tm_wday=6, tm_yday=343,
tm_isdst=0)

asctime():

This functions returns a readable format of local time

>>> tk=time.time()
>>> tp=time.localtime(tk)

>>> time.asctime(tp)

'Sun Dec 9 15:11:25 2018'

ctime():

This function returns string representation of system's current time

>>> time.ctime()

'Sun Dec 9 15:17:40 2018'

sleep():

This function halts current program execution for a specified duration in seconds.

>>> time.ctime()

'Sun Dec 9 15:19:14 2018'

>>> time.sleep(20)

>>> time.ctime()

'Sun Dec 9 15:19:34 2018'

Few more built-in modules will be discussed in separate subsequent chapters of this

tutorial.

 re module

 threading module

 cgi module

 tkinter module

 csv module

 pickle module

 socket module

 sqlite3 module

 json module

You might also like