0% found this document useful (0 votes)
3 views11 pages

Modules Notes

Python modules are scripts that encapsulate functions and classes, allowing for code reuse and easier collaboration among teams. Modules can be created by saving Python code in a .py file and can be imported into other scripts using the import statement. The document also covers built-in modules like math and random, detailing their functions and usage.

Uploaded by

prajwalchavan354
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Modules Notes

Python modules are scripts that encapsulate functions and classes, allowing for code reuse and easier collaboration among teams. Modules can be created by saving Python code in a .py file and can be imported into other scripts using the import statement. The document also covers built-in modules like math and random, detailing their functions and usage.

Uploaded by

prajwalchavan354
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Modules in Python.

What Are Python Modules


Modules are simply a ‘program logic’ or a ‘python script’ that can be used for a variety of
applications or functions. We can declare functions, classes, etc in a module.

The focus is to break down the code into different modules so that there will be no or
minimum dependencies on one another. Using modules in a code helps to write a lesser line
of codes, a single procedure developed for reuse of the code as well. It also eliminates the
need to write the same logic again and again.

One more advantage of using modules is that the programs can be designed easily since a
whole team works only on a part or module of the entire code.

How To Create Modules In Python


Creating a module in python is similar to writing a simple python script using the .py
extension. For the above example, lets try to make a module for the various operations.

def add(x,y):
return x + y

def sub(x, y):


return x - y

def prod(x, y):


return x * y

def div(x, y):


return x / y

Save the above code in a file [Link]. This is how we create a module in python. We have
created different functions in this module. We can use these modules in our main file, let us
take a look at how we are going to use them in a program.

How To Use Python Modules.

We will use the import keyword to incorporate the module into our program, from keyword
is used to get only a few or specific methods or functions from a module. Let us see what are
different methods to use a module in your program.

Let us say we have our file with a name [Link].

import calc as a
a = 10
b = 20

addition = [Link](a,b)
print(addition)
In the above code, we have created an alias using the “as” keyword. The output of the above
code will be the addition of the two numbers a and b using the logic specified in the add
function in the [Link] module.

Let us take a look at another approach.

from calc import *


a = 20
b = 30

print(add(a,b))

In the above code, we have imported all the functions using the asterisk and we can simply
mention the function name to get the results.

Python Module Path


When we import a module, the interpreter looks for the module in the build-in modules directories
in [Link] and if not found, it will look for the module in the following order:

import sys
print([Link])

When you run the above code, you will get the list of directories. You can make changes in
the list to create your own path.

Built-in modules are written in C and integrated with python interpreter. Each built-in module
contains resources for certain specific functionalities like Operating system management,
disk input/output etc.

The standard library also has many python scripts containing useful utilities. There are
several built-in modules in python at our disposal that we can use whenever we want.

To get the list of all the modules in python, you can write the following command in the
python console.

help('modules')

You will get a list of all the modules in python.

dir( ) Built-in Function

It returns a sorted list of strings containing the names defined in a module. The list contains
the names of all the variables, functions, classes, etc.

import calc
print(dir(calc))

In Python, you can use the import statement to import modules or files from different folders.
If the file you want to import is in a different folder than the script you are running, you will
need to specify the path to the file.
You can use the [Link]() function to add the path to the folder containing the file
you want to import. For example, if the file is located in a folder called my_folder in the same
directory as your script, you would use the following code to add the path to my_folder to the
system path:

import sys
[Link]("my_folder")

Then you can import the file as usual:

import my_file

Alternatively, you can use the PYTHONPATH environment variable to add the path to the
folder containing the file you want to import.

You can also use the importlib.import_module() function to import modules from different
folders by providing the full path of the module.

import importlib
module = importlib.import_module("[Link].my_module")

You can also use the from .. import to import module or files from different folders, if the
folder is in the same parent directory as the script you are running.

from ..my_folder import my_module

Note: use of .. is used to go one level up in the directory hierarchy.

math module in Python


Python math module is a standard module that is always accessible in Python to perform
simple mathematical calculations. To utilize the mathematical functions in this module, you
must first import it with import math. Importing math in Python provides access to the
Python math functions provided by the C standard. Any math function in Python can be
accessed by using a math class object.

Example

import math

print('Square root of 25 is:', [Link](25))


print('Value of pi is:', [Link])

Output:

Square root of 25 is: 5.0


Value of pi is: 3.141592653589793
Complex data types are not supported by this module. The complex counterpart is the cmath
module.

Functions in Python Math Module


All key Python math functions are deeply described below,

Constants – Python’s math module includes a number of preset constants. Having access to
these constants has a number of advantages. For starters, you won’t have to manually
hardcode them into your program, which will save you a significant amount of time.
Furthermore, they ensure consistency throughout your code. Examples, Euler’s number, pi,
infinity, tau, etc.

Logarithmic functions – A logarithm is the inverse of exponentiation. To determine the


logarithm value of any given number x, the exponent of another fixed number with base b is
determined. Examples, log, exponential, power, sqrt, etc.

Numeric functions – All mathematical inceptions can be calculated using the numeric
functions.

Trigonometric functions – Trigonometric functions are used in mathematics to describe the


point of view of a right-angled triangle with two side lengths. These Python math functions
include sin, cos, tan, etc.

The following is a list of all the functions and attributes specified in the math module, along
with a brief description of what they perform.

Function Description
ceil(x) The lowest integer bigger than or equal to x is returned.
copysign(x, y) Returns a number with the value ‘x’ but the sign ‘y.’
fabs(x) The absolute value of the number is returned.
factorial(x) The factorial of the number is returned.
floor(x) The greatest integer less than or equal to x is returned.
fmod(x, y) When x is divided by y, the residual is returned.
frexp(x) As a pair (m, e), this function returns the mantissa and exponent of x.
fsum(iterable) Returns an accurate floating-point sum of the iterable’s values.
isfinite(x) Check that the value is not infinity or Nan.
isinf(x) Check to see if the value is infinite or not.
isnan(x) If the number is “nan,” returns true; otherwise, returns false.
ldexp(x, i) x * (2**i) is returned.
modf(x) The fractional and integer components of x are returned.
trunc(x) The shortened integer value of x is returned.
exp(x) e**x is the result.
expm1(x) e**x – 1 is returned.
log(x[, b]) The logarithmic value of a with base b is returned.
log1p(x) 1+x’s natural logarithmic value is returned.
log2(x) Calculates the value of log a with base 2.
log10(x) This function computes the value of log a with a base of ten.
pow(x, y) Calculates the value of x raised to the power of y, i.e. (x**y).
sqrt(x) The square root of x is returned.
acos(x) The arc cosine of x is returned.
asin(x) The arc sine of x is returned.
atan(x) The arc tangent of x is returned.
atan2(y, x) atan(y / x) is returned.
cos(x) The cosine of x is returned.
hypot(x, y) Returns the Euclidean norm – sqrt(x*x + y*y)
sin(x) The sine of x is returned.
tan(x) The tangent of x is returned.
degrees(x) Angle x is converted from radians to degrees.
radians(x) Angle x is converted from degrees to radians.
The inverse hyperbolic cosine of the value supplied as input is
acosh(x)
returned.
asinh(x) The inverse hyperbolic sine of the value supplied as input is returned.
The inverse hyperbolic tangent of the value supplied as input is
atanh(x)
returned.
The hyperbolic cosine of the value supplied as an argument is
cosh(x)
returned.
sinh(x) The hyperbolic sine of the value supplied as an argument is returned.
tanh(x) The hyperbolic tangent of the value supplied as input is returned.
erf(x) The error function at x is returned.
erfc(x) The complementary error function at x is returned.
gamma(x) The Gamma function at x is returned.
Returns the natural logarithm of the absolute value of the Gamma
lgamma(x)
function at x
Mathematical constant, the circumference to diameter ratio of a circle
pi
(3.14159…)
e e is the mathematical constant (2.71828…)

Examples:

import math

print('Power of number:', [Link](2, 2))

print('Floor value is:', [Link](12.5473))


print('Ceil value is:', [Link](11.5473))

print('Factorial of number:', [Link](5))

print('modf of number:', [Link](10.45))

Python Random Module:


The Python random module provides a set of functions for generating random numbers,
selecting random elements from sequences, and shuffling collections. It is widely used in
simulations, cryptography, gaming, machine learning, and randomized testing. To use the
random module, you need to import it first. Once imported, you can use its various functions
to generate random numbers, shuffle lists, and select random elements.

Random numbers are widely used in simulations, cryptography, and statistical sampling.

Example:

import random

temperature = [Link](-10, 50) # Random float between -10°C and 50°C

print(f"Simulated temperature: {temperature:.2f}°C")

2. Selecting Random Elements from a List

When working with lists, [Link]() allows you to pick a random element.

colors = ["red", "blue", "green", "yellow"]

random_color = [Link](colors)

print(f"Randomly selected color: {random_color}")

3. Shuffling a List

Shuffling is useful in applications like card games, randomized testing, and playlist
randomization.

cards = ["Ace", "King", "Queen", "Jack", "10"]

[Link](cards)

print("Shuffled deck:", cards)


List of Functions in Python Random Module
Function Description
seed(a=None,
Initialize the random number generator
version=2)
Returns an object capturing the current internal state of the
getstate()
generator
setstate(state) Restores the internal state of the generator
getrandbits(k) Returns a Python integer with k random bits
randrange(start, stop[,
Returns a random integer from the range
step])
randint(a, b) Returns a random integer between a and b inclusive
choice(seq) Return a random element from the non-empty sequence
shuffle(seq) Shuffle the sequence
Return a k length list of unique elements chosen from the
sample(population, k)
population sequence
Return the next random floating point number in the range [0.0,
random()
1.0)
uniform(a, b) Return a random floating point number between a and b inclusive
triangular(low, high, Return a random floating point number between low and high,
mode) with the specified mode between those bounds
betavariate(alpha, beta) Beta distribution
expovariate(lambd) Exponential distribution
gammavariate(alpha,
Gamma distribution
beta)
gauss(mu, sigma) Gaussian distribution
lognormvariate(mu,
Log normal distribution
sigma)
normalvariate(mu,
Normal distribution
sigma)
vonmisesvariate(mu,
Vonmises distribution
kappa)
paretovariate(alpha) Pareto distribution
weibullvariate(alpha,
Weibull distribution
beta)

Time Module in Python

The Time Module is an integral part of Python, offering functionalities to work with dates,
times, and intervals. It facilitates tasks such as measuring execution time, scheduling events,
logging timestamps, and calculating time differences. These capabilities make it an
indispensable tool for time-related manipulations in programming.
What is epoch

The epoch is the point where the time starts and is platform-dependent. On Windows and
most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC), and leap seconds are not
counted towards the time in seconds since the epoch. To check what the epoch is on a given
platform we can use [Link](0).

Function Description
[Link]() returns the number of seconds that have
passed since the epoch.
[Link]() The [Link]() function in the time
module takes seconds as an argument,
computes the number of seconds passed
since the epoch, and returns a string
representing the local time in 24 characters
or mentioned milliseconds. If we don’t pass
any variable argument, it calculates the time
till the present.
[Link]() To delay or pause the execution of the
current thread for a specified number of
seconds. It halts the program execution or
delays it for the given time set in the

argument.
[Link]() The [Link]() function takes the
number of seconds passed since the epoch
as an argument and returns the struct_time
object (a tuple consisting of 9 elements
corresponding to struct_time) in local time.
If the seconds argument is not mentioned, it
uses the current time returned by the

[Link]() function.
[Link]() The [Link]() function in the time
module is the inverse function of the
[Link]() method. It takes the
struct_time (a tuple containing 9 elements
corresponding to struct_time) as an
argument and returns seconds passed since

the epoch as local time.


[Link]() converts the time expressed in seconds since
the epoch to the struct_time object in UTC,
in which the tm_isdst attribute is always set
to 0. It takes the number of seconds passed
since the epoch as a variable argument. If
seconds are not passed as a parameter, then
it uses the current time returned by the

[Link]() function.
[Link]() converts the time_struct object (a tuple
containing 9 elements of the struct_time)
representing the time obtained by
[Link]() or [Link]() method to
a string. Format is Day Mon Date
Hour:Min: Sec Year
[Link]() The strftime() function takes the struct_time
or tuple as a dynamic argument and
converts it representing time returned by
gmtime() or localtime() to a string as given
by the format argument. If time is not
passed as an argument, it takes the current
time as returned by the localtime() function,
where the format must be a string. If the
field is outside of the allowed range, it

raises a ValueError.
[Link]() converts a string representing the time to the

struct_time object.

time.struct_time Class

The time.struct_time class in the time module in Python helps us access the local time,
especially non-epochal timestamps. The output it returns is a named tuple whose value can be
accessed by attribute name and index. Several attributes are associated with the
time.struct_time object, which we have listed below:

Index Attribute Name Values

0 tm_year 0000, …, 9999

1 tm_mon 1, 2, …, 11, 12

2 tm_mday 1, 2, …, 30, 31

3 tm_hour 0, 1, …, 22, 23

4 tm_min 0, 1, …, 58, 59
5 tm_sec 0, 1, …, 60, 61

6 tm_wday 0, 1, …, 6; Sunday is 6

7 tm_yday 1, 2, …, 365, 366

8 tm_isdst 0, 1 or -1

Example
import time

# Get the current local time as a struct_time object

local_time = [Link]()

# Access attributes by name

print("Year:", local_time.tm_year)

print("Month:", local_time.tm_mon)

print("Day of the Month:", local_time.tm_mday)

print("Hour:", local_time.tm_hour)

print("Minute:", local_time.tm_min)

print("Second:", local_time.tm_sec)

print("Day of the Week:", local_time.tm_wday)

print("Day of the Year:", local_time.tm_yday)

print("Daylight Saving Time Flag:", local_time.tm_isdst)

# Access attributes by index

print("Year (index):", local_time[0])

print("Month (index):", local_time[1])

print("Day of the Month (index):", local_time[2])

print("Hour (index):", local_time[3])

print("Minute (index):", local_time[4])

print("Second (index):", local_time[5])

print("Day of the Week (index):", local_time[6])


print("Day of the Year (index):", local_time[7])

print("Daylight Saving Time Flag (index):", local_time[8])

Output:
Year: 2024
Month: 9
Day of the Month: 14
Hour: 12
Minute: 37
Second: 39
Day of the Week: 5
Day of the Year: 258
Daylight Saving Time Flag: 0
Year (index): 2024
Month (index): 9
Day of the Month (index): 14
Hour (index): 12
Minute (index): 37
Second (index): 39
Day of the Week (index): 5
Day of the Year (index): 258
Daylight Saving Time Flag (index): 0

You might also like