What Is Python Module
What Is Python Module
A Python module is a file containing Python definitions and statements. A module can define
functions, classes, and variables. A module can also include runnable code.
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
-------
return (x+y)
return (x-y)
We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches for
importing a module. For example, to import the module calc.py, we need to put the following
command at the top of the script.
-----
import module
Now, we are importing the calc that we created earlier to perform add operation.
-----
import calc
print(calc.add(10, 2))
Python Import From Module
Python’s from statement lets you import specific attributes from a module without importing the
module as a whole.
Here, we are importing specific sqrt and factorial attributes from the math module.
----
# module math
# are required.
print(sqrt(16))
print(factorial(6))
The * symbol used with the import statement is used to import all the names from a module to a
current namespace.
Syntax:
Whenever a module is imported in Python the interpreter looks for several locations. First, it will
check for the built-in module, if not found then it looks for a list of directories defined in the sys.path.
Python interpreter searches for the module in the following manner –
Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the
interpreter will search for the required module.
Example:
import sys
# importing sys.path
print(sys.path)
Syntax:
There are several built-in modules in Python, which you can import whenever you like.
import math
# in math module
print(math.sqrt(25))
print(math.pi)
print(math.degrees(2))
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
import random
print(random.randint(0, 5))
print(random.random())
print(random.random() * 100)
print(random.choice(List))
import datetime
from datetime import date
import time
print(time.time())
print(date.fromtimestamp(454554))
The reload() is a previously imported module. If you’ve altered the module source file using an
outside editor and want to test the updated version without leaving the Python interpreter, this is
helpful. The module object is the return value.
Example:
import imp
imp.reload(module)
Python Packages
Python modules may contain several classes, functions, variables, etc. whereas Python packages
contain several modules. In simpler terms, Package in Python is a folder that contains various
modules as files.
Creating Package
Let’s create a package in Python named mypckg that will contain two modules mod1 and mod2. To
create this module follow the below steps:
def gfg():
print("Welcome to GFG")
Mod2.py
return a+b
Understanding __init__.py
__init__.py helps the Python interpreter recognize the folder as a package. It also specifies the
resources to be imported from the modules. If the __init__.py is empty this means that all the
functions of the modules will be imported. We can also specify the functions from each module to be
made available.
For example, we can also create the __init__.py file for the above module as:
__init__.py
We can import these Python modules using the from…import statement and the dot(.) operator.
Syntax:
import package_name.module_name
What are Decision Making Statements in Python?
Programming requires decision-making statements because they let programs decide what to do and
run distinct code blocks according to predefined conditions. The if, elif and if-else statements are just
a few of the decision-making statements available in Python. Programmers can control how a
program executes depending on a variety of conditions by using these statements.
There are four types of decision-making statements in Python language, those are
• If statements in python
• If else statement in python
• Nested if else statement in python
• if-elif-else Ladder in python
Example of If Statements:
num = 8
if num > 0:
• If the condition in the if block evaluates to false, the if-else statement executes an alternate
block of code.
• This block of alternatives is introduced by the else keyword.
Example:
num = 11
if num % 2 == 0:
else:
Example:
num = 3
if num > 0:
if num % 2 == 0:
else:
else:
Example:
x = 11
if x == 2:
elif x == 3:
elif x == 4:
else:
Loops in Python
Python programming language provides the following types of loops to handle looping requirements.
Python provides three ways for executing the loops.
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the program
is executed.
count = 0
print("Hello World")
The else clause is only executed when your while condition becomes false. If you break out of the
loop, or if an exception is raised, it won’t be executed.
while condition:
else:
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In
Python, there is “for in” loop which is similar to for each loop in other languages. Let us learn how to
use for in loop for sequential traversals.
statements(s)
Example:
n=4
print(i)
Loop control statements change execution from their normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.
Continue Statement
The continue statement in Python returns the control to the beginning of the loop.
continue
break
Pass Statement
We use pass statement in Python to write empty loops. Pass is also used for empty control
statements, functions and classes.
Python Classes and Objects
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a
means of bundling data and functionality together. Creating a new class creates a new type of object,
allowing new instances of that type to be made. Each class instance can have attributes attached to it
for maintaining its state. Class instances can also have methods (defined by their class) for modifying
their state.
class ClassName:
# Statement
obj = ClassName()
print(obj.atrr)
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
# Object instantiation
Rodger = Dog()
print(Rodger.attr1)
Rodger.fun()
The built-in class attributes provide us with information about the class.
Using the dot (.) operator, we may access the built-in class attributes.
Attributes Description
__bases__ A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.
class destructor:
def __init__(self):
def __del__(self):
# create an object
Object = destructor();
del Object;