Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

What Is Python Module

This document discusses Python modules, packages, and importing. It explains what modules are, how to create and import modules, and the different ways to import attributes from modules. It also covers Python packages, reloading modules, and locating modules.

Uploaded by

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

What Is Python Module

This document discusses Python modules, packages, and importing. It explains what modules are, how to create and import modules, and the different ways to import attributes from modules. It also covers Python packages, reloading modules, and locating modules.

Uploaded by

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

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.

Create a Python Module

Let’s create a simple calc.py in which we define two functions, one add and another subtract.

-------

# A simple module, calc.py

def add(x, y):

return (x+y)

def subtract(x, y):

return (x-y)

Import module in Python

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.

Syntax of Python Import

-----

import module

Importing modules in Python Example

Now, we are importing the calc that we created earlier to perform add operation.

-----

# importing module calc.py

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.

Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the math module.

----

# importing sqrt() and factorial from the

# module math

from math import sqrt, factorial

# if we simply do "import math", then

# math.sqrt(16) and math.factorial()

# are required.

print(sqrt(16))

print(factorial(6))

Import all Names

The * symbol used with the import statement is used to import all the names from a module to a
current namespace.

Syntax:

from module_name import *

Locating Python Modules

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 –

• First, it searches for the module in the current directory.


• If the module isn’t found in the current directory, Python then searches each directory in the
shell variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list
of directories.
• If that also fails python checks the installation-dependent list of directories configured at the
time Python is installed.

Directories List for Modules

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:

# importing sys module

import sys

# importing sys.path

print(sys.path)

Renaming the Python module

We can rename the module while importing it using the keyword.

Syntax:

Import Module_name as Alias_name

Python Built-in modules

There are several built-in modules in Python, which you can import whenever you like.

# importing built-in module math

import math

# using square root(sqrt) function contained

# in math module

print(math.sqrt(25))

# using pi function contained in math module

print(math.pi)

# 2 radians = 114.59 degrees

print(math.degrees(2))

# 60 degrees = 1.04 radians

print(math.radians(60))

# Sine of 2 radians

print(math.sin(2))
# Cosine of 0.5 radians

print(math.cos(0.5))

# Tangent of 0.23 radians

print(math.tan(0.23))

# 1 * 2 * 3 * 4 = 24

print(math.factorial(4))

# importing built in module random

import random

# printing random integer between 0 and 5

print(random.randint(0, 5))

# print random floating point number between 0 and 1

print(random.random())

# random number between 0 and 100

print(random.random() * 100)

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing

# a random element from a set such as a list

print(random.choice(List))

# importing built in module datetime

import datetime
from datetime import date

import time

# Returns the number of seconds since the

# Unix Epoch, January 1st 1970

print(time.time())

# Converts a number of seconds to a date object

print(date.fromtimestamp(454554))

Reloading modules in Python

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)

How do I unload a Python module?

Unloading a Python module is not possible in Python yet.

Python Packages

What is a Python Package?

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:

• Create a folder named mypckg.


• Inside this folder create an empty Python file i.e. __init__.py
• Then create two modules mod1 and mod2 in this folder.
Mod1.py

def gfg():

print("Welcome to GFG")

Mod2.py

def sum(a, b):

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

from .mod1 import gfg

from .mod2 import sum

Import Modules from a Package

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.

Types of decision-making statements in python

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:

print("The number is positive.")

If else statement in python

• 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:

print("The number is even.")

else:

print("The number is odd.")

Nested if else statement in Python

• Python enables the nesting of decision-making statements, which facilitates the


development of more complex decision logic.
• A hierarchy of conditions can be created by an if or if-else block within another if or if-else
block.

Example:

num = 3

if num > 0:
if num % 2 == 0:

print("The number is positive and even.")

else:

print("The number is positive but odd.")

else:

print("The number is not positive.")

Python if-elif-else Ladder

• An if-elif-else ladder is an order of if statements connected by elif statements.


• This enables you to check for numerous conditions and run separate code blocks based on
which condition is met.

Example:

x = 11

if x == 2:

print("x is equal to 2")

elif x == 3:

print("x is equal to 3")

elif x == 4:

print("x is equal to 4")

else:

print("x is not equal to 2, 3, or 4")

Loops in Python

Python programming language provides the following types of loops to handle looping requirements.
Python provides three ways for executing the loops.

While Loop in Python

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.

While Loop Syntax/Example:

count = 0

while (count < 3):


count = count + 1

print("Hello World")

Using else statement with While Loop in Python

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.

Syntax of While Loop with else statement:

while condition:

# execute these statements

else:

# execute these statements

For Loop in Python

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.

For Loop Syntax:

for iterator_var in sequence:

statements(s)

Example:

n=4

for i in range(0, n):

print(i)

Loop Control Statements

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.

for letter in 'elephants':

if letter == 'e' or letter == 's':

continue

print('Current Letter :', letter)


Break Statement

The break statement in Python brings control out of the loop.

for letter in 'elephants':

if letter == 'e' or letter == 's':

break

print('Current Letter :', letter)

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.

Syntax: Class Definition

class ClassName:

# Statement

Syntax: Object Definition

obj = ClassName()

print(obj.atrr)

Some points on Python class:

• Classes are created by keyword class.


• Attributes are the variables that belong to a class.
• Attributes are always public and can be accessed using the dot (.) operator. Eg.: My
class.Myattribute

Example of Class and Object:

# Python3 program to

# demonstrate instantiating

# a class

class Dog:

# A simple class

# attribute

attr1 = "mammal"

attr2 = "dog"

# A sample method

def fun(self):

print("I'm a", self.attr1)

print("I'm a", self.attr2)


# Driver code

# Object instantiation

Rodger = Dog()

# Accessing class attributes

# and method through objects

print(Rodger.attr1)

Rodger.fun()

Built-In Class Attributes in Python

The built-in class attributes provide us with information about the class.

Using the dot (.) operator, we may access the built-in class attributes.

The built-in class attributes in python are listed below −

Attributes Description

__dict__ Dictionary containing the class namespace

__doc__ If there is a class documentation class, this returns it. Otherwise,


None

__name__ Class name.

__module__ Module name in which the class is defined. This attribute is


"__main__" in interactive mode.

__bases__ A possibly empty tuple containing the base classes, in the order of
their occurrence in the base class list.

Garbage Collection in Python

Garbage collection is a memory management technique used in programming languages to


automatically reclaim memory that is no longer accessible or in use by the application. It helps
prevent memory leaks, optimize memory usage, and ensure efficient memory allocation for the
program.

How to destroy an object in Python?

When an object is deleted or destroyed, a destructor is invoked. Before terminating an object,


cleanup tasks like closing database connections or filehandles are completed using the destructor.
The garbage collector in Python manages memory automatically. for instance, when an object is no
longer relevant, it clears the memory.

Code for Destructor:

# creating a class named destructor

class destructor:

# initializing the class

def __init__(self):

print ("Object gets created");

# calling the destructor

def __del__(self):

print ("Object gets destroyed");

# create an object

Object = destructor();

# deleting the object

del Object;

You might also like