Tuesday, 19 November 2024

Modules and Regular Expressions in Python.



 

Everyone knows what function is. A block of reusable code that performs specific task. Through function we can organize the code properly, making it more readable and reusable.

Now, question comes to mind that what is a module? why do we require module? How to create a module?

Let's first start with the question why do we require module?

To enhance the modularity of code or project, you can wrap or define more than one related function together and load these functionalities inside another program as and when required.

what is a module?

A module is a block or file consist of classes, variables, constants, definition of functions or any other python object.

or

A file containing more than one related function you want to include in your program just like a code library.

can any program access this module for reusability?

Yes, all the content available inside this module made available to any other program.

Now, next question comes to our mind is how we can access this in our program but before this How to create a module?

Let's create a simple module:

Step 1: First decide what name you want to give to your module. for example, if i want to create "JSPM" module.

Step 2: Create a file JSPM.py and write all the related code inside this file to make it a module.

def welcome (name):

    print ("Hello, "+name+ "Welcome to JSPM University")


# Can we create object of subject's information in module?

Yes,

FPP = {
  "Teachername""Nitin Shivale",
  "age"36,
  "Subjectname""Fundamentals of python programming"
}


Step 3: JSPM Module is created with one welcome () function and one variable FPP of type dictionary in it. As we know we can create variable of all types like array, dictionary, objects etc. Now next task is we want to access all the functionalities available inside JSPM Module in another program. so, how we are going to access it?

Step 4: Suppose i have created the python file of name Admission.py and inside this file i want to write a code to greet all the students who are taking admission in JSPM University. Now we know that functionality is already available inside JSPM Module. no need to write same code once again so simply reuse that code by importing the functionality of that module inside our program.


import JSPM

name = input ("Enter the name of newly admitted student:")

JSPM.welcome (name)

After execution of this code message will display as follows:

Enter the name of newly admitted student: Tejas Bhosale

suppose if you enter the name = "Tejas Bhosale" then it will give us the output: Hello Tejas Bhosale Welcome to JSPM University

Can i create alias of my module and use it to access the functionality of module?

Yes, we can do this it's very simple just use the as keyword to do this.

import JSPM as ju

a = ju.FPP["Teachername"]
print(a)

Here after execution, you will get the output as follows:

Nitin Shivale


Q. Can i import only the required functionalities from the module instead of importing whole module?

Yes, you can suppose from the above example instead of calling all the functionalities i just wanted to import only dictionary variable that is FPP then see how i can do this.

from JSPM import FPP

print (FPP["Teachername"]) #output: Nitin Shivale

print (FPP["age"]) #Output: 36

print (FPP["Subjectname"]) #Output: Fundamentals of python programming


Module Search Path:

When we are importing the module in our program from where exactly it is located and gets loaded in our program is the next question comes to our mind.

Q. How the module search path works in the Python?

When you import module in your program for example, in our above example when we write import JSPM. 

What will happen where the python will search that module let's learn this first:

Python will search for the JSPM.py file from the following sources:

  • The current folder from which the program executes.
  • A list of folders specified in the PYTHONPATH environment variable, if you set it before.
  • An installation-dependent list of folders that you configured when you installed Python.

Python stores the resulting search path in the sys.path variable that comes from the sys module.

If we want to check how many paths are there inside sys.path variable, then we can check this by writing following code.

import sys

for path in sys.path:
    print(path)

To make sure Python can always find the module.py, you need to:

  • Keep module.py in the folder where the program will run.
  • Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can keep the module.py in one of the folders included in the PYTHONPATH variable.
  • Place the module.py in one of the installation-dependent folders.

Note:

>> import sys
>> sys.path.append('H:\\modules\\')

Python allows you to modify the module search path at runtime by modifying the sys.path variable. This allows you to store module files in any folder of your choice.

Since the sys.path is a list, you can append a search-path to it.


Q. What is Loading and Reloading of Module?

To load a module, we use the import statement. for e.g. to load JSPM module we write import JSPM

Why we have to reload module once it is loaded?
As we know there is always an improvement in every project's functionality likewise in our module also certain things are going to be added or changed after some times. 
To make available those newly added functionality to the code or program which one imported this module in it. we have to reload that module in once again in that program. 
Remember by using reload () function we can reload the module just you have to pass that module object name as an argument to reload () function.

For e.g. 

import sys
import JSPM
JSPM.reload(sys)

Q. What is dir () function?

In Python, the dir() function is a built-in function used to list the attributes (methods, properties, and other members like module, string, list, dictionaries, etc.) of an object.

Syntax: dir({object})

Parameter: dir([optional]): Here it takes object name

Returns:
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. 


  • For Class Objects, it returns a list of names of all the valid attributes and base attributes as well. 
  • For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module. 
  • If no parameters are passed it returns a list of names in the current local scope.
Example:

# Python3 code to demonstrate dir()
# when no parameters are passed
# Note that we have not imported any modules
print(dir())
 
# Now let's import two modules
import sys
import math
 
print(dir())


Output
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '...

When User Defined Objects are Passed as Parameters

# Creation of a simple class with __dir()__
# method to demonstrate it's working
class jspmbsiotr:
 
    # Function __dir()___ which list all
    # the base attributes to be used.
    def __dir__(self):
        return ['college_name', 'principal',
               'intake', 'department', 'address']
 
 
# user-defined object of class jspmbsiotr
my_college = jspmbsiotr()
 
# listing out the dir() method
print(dir(my_college))


Output
['address', 'college_name', 'department', 'intake', 'principal']

Math Module:

The Math Module in Python provides all variety of mathematical functions including constants and Operations. Following program shows us the basic functionalities provided by the math module.

# Import the math module

import math


# Constants provided by the math module

print ("Math Constants:")

print ("Value of pi:", math.pi)  # 3.141592653589793

print ("Value of e:", math.e)    # 2.718281828459045


# Basic mathematical functions

print ("\nBasic Functions:")

number = -25

print (f"Absolute value of {number}: {math.fabs(number)}") # Absolute value

number = 16

print (f"Square root of {number}: {math.sqrt(number)}") # Square root


Trigonometric functions

angle = math.pi / 4 # 45 degrees in radians

print (f"Sine of 45 degrees: {math.sin(angle)}") # Trigonometric sine

print (f"Cosine of 45 degrees: {math.cos(angle)}") # Trigonometric cosine

print (f"Tangent of 45 degrees: {math.tan(angle)}") # Trigonometric tangent


# Logarithmic functions

print ("\nLogarithmic Functions:")

number = 10

print (f"Natural logarithm (ln) of {number}: {math.log(number)}")

print (f"Base-10 logarithm (log10) of {number}: {math.log10(number)}")


# Exponential functions

print ("\nExponential Functions:")

exponent = 2

print (f"e raised to the power of {exponent}: {math.exp(exponent)}")

base = 2

power = 3

print(f"{base} raised to the power of {power}: {math.pow(base, power)}")


# Rounding functions

print ("\nRounding Functions:")

number = 4.7

print (f"Floor of {number}: {math.floor(number)}") # Rounds down

print (f"Ceiling of {number}: {math.ceil(number)}") # Rounds up


# Factorial

print("\nFactorial:")

number = 5

print (f"Factorial of {number}: {math.factorial(number)}")


# GCD (Greatest Common Divisor)

print ("\nGCD (Greatest Common Divisor):")

a = 48

b = 18

print (f"GCD of {a} and {b}: {math.gcd(a, b)}")


# Degrees and Radians Conversion

print ("\nDegree and Radian Conversions:")

angle_in_degrees = 180

angle_in_radians = math.radians(angle_in_degrees)

print(f"{angle_in_degrees} degrees in radians: {angle_in_radians}")

print(f"{angle_in_radians} radians in degrees: {math.degrees(angle_in_radians)}")


data structures and algorithms Web Developer

No comments:

Post a Comment