0% found this document useful (0 votes)
12 views

Unit 5 Modules

Python Programming

Uploaded by

jayjoshi80208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Unit 5 Modules

Python Programming

Uploaded by

jayjoshi80208
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Unit 5: Modules

Prepared By:
Tanvi Patel
Asst. Prof. (CSE)
Contents

◉ Introduction to Modules
◉ Types of Modules
◉ Math Module
◉ Random Module
◉ Datetime module
◉ Sys module
◉ OS module

◉ NOTE: For math,random and datetime module refer colab shared file.
What are modules?

◉ Modules refer to a file containing Python statements and definitions.


◉ We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
◉ We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
◉ Python import statement
◉ We can import a module using the import statement and access the definitions inside it using the
dot operator as described above. Here is an example.
import math
print("The value of pi is", math.pi)
Module Rename

◉ Import with renaming


◉ We can import a module by renaming it as follows:
import math as m
print("The value of pi is", m.pi)
◉ We have renamed the math module as m. This can save us typing time in some
cases.
◉ Note that the name math is not recognized in our scope. Hence, math.pi is invalid,
and m.pi is the correct implementation.
Python from...import statement

◉ Python from...import statement


◉ We can import specific names from a module without importing the module as a
whole. Here is an example.
from math import pi
print("The value of pi is", pi)
◉ Here, we imported only the pi attribute from the math module.
◉ In such cases, we don't use the dot operator. We can also import multiple attributes
as follows:
from math import pi, e
Import all names

Import all names


◉ We can import all names(definitions) from a module using the following construct:
from math import *
print("The value of pi is", pi)
◉ Here, we have imported all the definitions from the math module. This includes all
names visible in our scope except those beginning with an underscore(private
definitions).
◉ Importing everything with the asterisk (*) symbol is not a good programming
practice. This can lead to duplicate definitions for an identifier. It also hampers the
readability of our code.
Types of Modules

There are two types of modules:


1. User defined module for our own purpose.
2. Inbuilt modules like math,random,os,sys etc.
◉ To create user defined module: Create a file with below code in any editor/IDE and
save as custom_module.py
def add(a, b):
"""This program adds two
numbers and return the result"""
result = a + b
return result
Types of Modules (Cont.)

◉ To import user defined module,


use import then filename, in our
case import custom_module.
◉ Then inside custom_module
you can use all functions,
methods defined inside the file
as shown in fig.
Math Module

◉ The math module is a standard module in Python and is always available. To use
mathematical functions under this module, you have to import the module
using import math.
◉ It provides us access to some common math functions and constants in Python,
which we can use throughout our code for more complex mathematical
computations.
◉ The library is a built-in Python module, therefore you don't have to do any
installation to use it.
◉ For example,
# Square root calculation
import math
math.sqrt(4)
Math Module (Cont.)

Special Constants
◉ The Python Math Library contains two important constants.
◉ Pie
◉ The first one is Pie (π), a very popular math constant. It denotes the ratio of circumference to
diameter of a circle and it has a value of 3.141592653589793. To access it, we first import the
Math Library as follows:
◉ import math
◉ We can then access this constant using pi:
◉ math.pi
◉ Output
◉ 3.141592653589793
◉ You can use this constant to calculate the area or circumference of a circle.
Math Module (Cont.)

◉ Euler's Number
◉ The Euler's number (e), which is the base of natural logarithm is also defined in the Math library.
We can access it as follows:
◉ math.e
◉ Output
◉ 2.718281828459045
◉ The following example demonstrates how to use the above constant:
◉ import math
◉ print((math.e + 6 / 2) * 4.32)
◉ Output
◉ 24.702977498943074
Math Module (Cont.)

◉ Exponents and Logarithms


◉ In this section, we will explore the Math library functions used to find different types of exponents
and logarithms.
◉ The exp() Function
◉ The Python Math Library comes with the exp() function that we can use to calculate the power
of e. For example, ex, which means the exponential of x. The value of e is 2.718281828459045.
◉ The method can be used with the following syntax:
◉ math.exp(x)
◉ The parameter x can be a positive or negative number. If x is not a number, the method will
return an error.
Math Module (Cont.)
Math Module (Cont.)

◉ We can also apply this method to inbuilt constants as demonstrated below:


◉ import math
◉ print(math.exp(math.e))
◉ print(math.exp(math.pi))
◉ If you pass a non-numeric value to the method, it will generate an error, as demonstrated here:

Math Module (Cont.)

◉ The log() Function


◉ This function returns the logarithm of the specified number. The natural logarithm is computed
with respect to the base e. The following example demonstrates the usage of this function:
Math Module (Cont.)

◉ The log10() Function


◉ This method returns the base-10 logarithm of the specified number. For example:

◉ The log2() Function


◉ This function calculates the logarithm of a number to base 2.
Math Module (Cont.)

◉ The log(x, y) Function


◉ This function returns the logarithm of x with y being the base. For example:
Math Module (Cont.)

Arithmetic Functions
◉ Arithmetic functions are used to represent numbers in various forms and perform mathematical
operations on them. Some of the most common arithmetic functions are discussed below:
◉ ceil(): returns the ceiling value of the specified number.
◉ fabs(): returns the absolute value of the specified number.
◉ floor(): returs the floor value of the specified number.
◉ gcd(a, b): returns the greatest common divisor of a and b.
◉ fsum(iterable): returns the sum of all elements in an iterable object.
◉ expm1(): returns (e^x)-1.
◉ exp(x)-1: when the value of x is small, calculating exp(x)-1 may lead to a significant loss in
precision. The expm1(x) can return the output in with full precision.
Math Module (Cont.)
Math Module (Cont.)

◉ Other math functions include the following:


◉ pow(): takes two float arguments and raises the first argument to the second argument and
returns the result. For example, pow(2,2) is equivalent to 2**2.
◉ sqrt(): returns the square root of the specified number.
◉ Power:
◉ math.pow(3, 4)
◉ Output: 81.0
◉ Square Root:
◉ math.sqrt(81)
◉ Output: 9.0
Math Module (Cont.)

◉ Trigonometric Functions
◉ The Python Math module supports all the trigonometric functions. Some of them have been
enlisted below:
◉ sin(a): Returns the sine of "a" in radians
◉ cos(a): Returns the cosine of "a" in radians
◉ tan(a): Returns the tangent of "a" in radians
◉ asin(a): Returns the inverse of sine. Also, there are "atan" and "acos".
◉ degrees(a): Converts an angle "a" from radian to degrees.
◉ radians(a): Converts angle "a" from degrees to radian.
Math Module (Cont.)

◉ Note that we first converted the value of the angle from degrees to radians before performing the
other operations.
Math Module (Cont.)

◉ Conclusion
◉ The Python Math Library provides us with functions and constants that we can use
to perform arithmetic and trigonometric operations in Python. The library comes
installed in Python, hence you are not required to perform any additional installation
in order to be able to use it. For more info you can find the official documentation
here.
Random Module

◉ You can generate random numbers in Python by using random module.


◉ It can be used perform some action randomly such as to get a random number,
selecting a random elements from a list, shuffle elements randomly, etc.
◉ The Python random module functions depend on a pseudo-random number
generator function random(), which generates the float number between 0.0 and
1.0.
Random Module (Cont.)

◉ random.random()
◉ This function generates a random float number between 0.0 and 1.0.
◉ random.randint()
◉ This function returns a random integer between the specified integers.
◉ random.choice()
◉ This function returns a randomly selected element from a non-empty sequence.
Random Module (Cont.)
Random Module (Cont.)

◉ random.shuffle()
This function randomly reorders the elements in the list.
◉ random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its
argument. It accepts three arguments, beginning number, last number, and step,
which is used to skip a number in the range.
◉ random.seed()
This function is used to apply on the particular random number with the seed
argument.
The generator creates a random number based on the seed value, so if the seed val
ue is 10, you will always get 0.5714025946899135 as the first random number.
Random Module (Cont.)
Random Module (Cont.)

Function Description

seed(a=None, version=2) Initialize the random number generator

randint(a, b) Returns a random integer between a and b inclusive

Return a random element from the non-empty


choice(seq)
sequence

shuffle(seq) Shuffle the sequence

getrandbits(k) Returns a Python integer with k random bits

randrange(start, stop[, step]) Returns a random integer from the range


Random Module (Cont.)

Function Description

Return a k length list of unique elements chosen from


sample(population, k)
the population sequence

Return the next random floating point number in the


random()
range [0.0, 1.0)

Return a random floating point number between a and


uniform(a, b)
b inclusive

Returns an object capturing the current internal state


getstate()
of the generator

setstate(state) Restores the internal state of the generator

Return a random floating point number between low


triangular(low, high, mode) and high, with the specified mode between those
bounds

Returns a random float number based on the


expovariate(lambd)
Exponential distribution (used in statistics)
Random Module (Cont.)

Function Description

Returns a random float number based on the Gamma


gammavariate(alpha, beta)
distribution (used in statistics)

gauss(mu, sigma) Gaussian distribution

lognormvariate(mu, sigma) Log normal distribution

normalvariate(mu, sigma) Normal distribution

vonmisesvariate(mu, kappa) Vonmises distribution

paretovariate(alpha) Pareto distribution

weibullvariate(alpha, beta) Weibull distribution

betavariate(alpha, beta) Beta distribution


Python datetime

◉ The datetime module is used to modify date and time objects in various ways. It contains five
classes to manipulate date and time.
◉ They are as follows:
◉ Date: deals with date objects.
◉ Time: deals with time objects.
◉ datetime: deals with date and time object combinations.
◉ timedelta: deals with intervals of time. Used in calculations of past and future date and time
objects.
◉ Info: deals with time zone info of local time.
Python datetime (Cont.)

◉ To create and modify new date and time objects, we need to import the module. We load them
by using the following statement.
◉ import datetime
◉ Or if you want only one of the modules-
◉ from datetime import date
◉ from datetime import time
◉ from datetime import datetime
◉ We could create new objects that have different date and time stored for manipulation using the
datetime module.
◉ The following syntax would do the needful.
◉ import datetime
◉ datetime.datetime(year_number, month_number, date_number, hours_number,
minutes_number, seconds_number)
Python datetime

◉ Example 1: Get Current Date and Time

◉ Here, we have imported datetime module using import datetime statement.


◉ One of the classes defined in the datetime module is datetime class. We then
used now() method to create a datetime object containing the current local date and time.
Python datetime (Cont.)

Example 2: Get Current Date

◉ In this program, we have used today() method defined in the date class to get a date object
containing the current local date.
Python datetime (Cont.)

◉ import datetime
◉ print (datetime.date.today())
◉ Or
◉ from datetime import date
◉ print (date.today())
◉ To access individuals:
◉ now = date.today()
◉ print (now.day)
◉ print (now.month)
◉ print (now.year)
Python datetime (Cont.)

◉ You could also use the date class to find out the weekday of the current date
◉ Here is the Weekday Table which start with Monday as 0 and Sunday as 6.
◉ from datetime import date
Day WeekDay Number
◉ now = date.today()
Monday 0
◉ print (now.weekday())
Tuesday 1
Wednesday 2
Thursday 3
Friday 4
Saturday 5
Sunday 6
Python datetime (Cont.)

◉ What's inside datetime?


◉ We can use dir() function to get a list containing all attributes of a module.
Python datetime (Cont.)

◉ Usages of Datetime Module


◉ It is a powerful feature that allows us to manipulate system date and time without risking any system changes.
We can define a new date object and modify its representation.
◉ Arithmetic calculations can be done on the date and time objects for several purposes such as finding the future
date, the present year, formatting of date into strings, creating a time management solution, etc.
Sys Module

◉ The python sys module provides functions and variables which are used to
manipulate different parts of the Python Runtime Environment. It lets us access
system-specific parameters and functions.

◉ import sys
◉ First, we have to import the sys module in our program before running any
functions.
Sys Module (Cont.)

◉ sys.modules
◉ This function provides the name of the existing python modules which have been imported.
◉ sys.argv
◉ This function returns a list of command line arguments passed to a Python script. The name of
the script is always the item at index 0, and the rest of the arguments are stored at subsequent
indices.
◉ sys.exit
◉ This causes the script to exit back to either the Python console or the command prompt. This is
generally used to safely exit from the program in case of generation of an exception.
◉ sys.platform
◉ This value of this function is used to identify the platform on which we are working.
Sys Module (Cont.)

◉ sys.maxsize
◉ Returns the largest integer a variable can take.
◉ sys.version
◉ This attribute displays a string containing the version number of the current Python
interpreter.
◉ sys.copyright
◉ This String just displays the copyright information on currently installed Python
version.
◉ sys.path
◉ This is an environment variable that is a search path for all Python modules.
◉ sys.getrecursionlimit() #Get maximal recursion depth
OS Module

◉ Python OS module provides the facility to establish the interaction between the user
and the operating system. It offers many useful OS functions that are used to
perform OS-based tasks and get related information about operating system.
◉ The OS comes under Python's standard utility modules. This module offers a
portable way of using operating system dependent functionality.
◉ The Python OS module lets us work with the files and directories.
OS Module (Cont.)

◉ os.getcwd(): Function os.getcwd(), returns the Current Working Directory(CWD) of


the file used to execute the code, can vary from system to system.
OS Module (Cont.)

◉ os.chdir(): The os module provides the chdir() function to change the current
working directory.
OS Module (Cont.)

◉ os.listdir(): The listdir() function lists all the folders and files in the directory.
◉ os.rmdir(): The rmdir() function removes the specified directory with an absolute or
related path. First, we have to change the current working directory and remove the
folder.
OS Module (Cont.)

◉ os.mkdir(): Makes a folder in the current working directory.


OS Module (Cont.)

◉ os.makedirs(): Makes a folder and subfolder in the current working directory.


OS Module (Cont.)

◉ os.rename(): Renames the file in the current working directory.


Thank You

You might also like