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

Python Unit 4 Part 2

The document discusses Python modules and classes. It explains that a Python module is a file containing functions, classes or variables that can be imported and used in other Python files. It provides examples of built-in and custom modules. It also explains that classes are user-defined blueprints for creating objects with properties and methods.

Uploaded by

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

Python Unit 4 Part 2

The document discusses Python modules and classes. It explains that a Python module is a file containing functions, classes or variables that can be imported and used in other Python files. It provides examples of built-in and custom modules. It also explains that classes are user-defined blueprints for creating objects with properties and methods.

Uploaded by

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

Python Modules

A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python code
file saved with the extension (.py) is treated as the module. We may have a runnable code inside
the python module.

Built-in Modules in Python


The Python interpreter has a number of built-in functions. They are loaded automatically as the
interpreter starts and are always available.

For example, print() and input() for I/O, number conversion functions int(), float(), complex(),
data type conversions list(), tuple(), set(), etc.

Python - Math Module


Some of the most popular mathematical functions are defined in the math module. These include
trigonometric functions, representation functions, logarithmic functions, angle conversion
functions, etc. In addition, two mathematical constants are also defined in this module.

Fisrt we will import math module by writing it on console or editor and then we will use its
functions.

>>> import math

1. Pie (π) is a well-known mathematical constant, which is defined as the ratio of the
circumference to the diameter of a circle and its value is 3.141592653589793.

>>>math.pi
3.141592653589793

2. The following statements show sin, cos and tan ratios for the angle of 30 degrees
(0.5235987755982988 radians):

>>math.sin(0.5235987755982988)
0.49999999999999994

>>>math.cos(0.5235987755982988)
0.8660254037844387

>>>math.tan(0.5235987755982988)
0.5773502691896257

You may recall that sin(30)=0.5, cos(30)=32 (which is 0.8660254037844387) and tan(30)= 13
(which is 0.5773502691896257).
3. math.log()
The math.log() method returns the natural logarithm of a given number. The natural logarithm is
calculated to the base e.

>>>math.log(10)
2.302585092994046

4. math.exp()
The math.exp() method returns a float number after raising e (math.e) to given number. In other
words, exp(x) gives e**x.

>>>math.exp(10)
1.0

5. math.pow()
The math.pow() method receives two float arguments, raises the first to the second and returns
the result. In other words, pow(4,4) is equivalent to 4**4.

>>>math.pow(2,4)
16.0
>>>2**4
16

6. math.sqrt()
The math.sqrt() method returns the square root of a given number.

>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772

The following two functions are called representation functions. The ceil() function
approximates the given number to the smallest integer, greater than or equal to the given floating
point number. The floor() function returns the largest integer less than or equal to the given

>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4
Create a Module
To create a module you want to just save the code you want in a file with the file extension .py:

Example

Save this code in a file named firstmodule.py

def greetings(name):
print("Hello, " + name)

Here we are creating a function with the function name greetings and will save it and will use it
as a module.

Loading the module in our python code


After creating the module, now it is time to use it or load the module in other function or module.
For this we need to load the module in our python code to use its functionality. Python provides
two types of statements as defined below.
1. The import statement
2. The from-import statement

The import statement

The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as
the module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.

For example, if we are using ms word, in which there are many graphical and logical functions
used, and there are also some shortcut keys, while working on ms word, we call many such
functions to use it in our work.

Also, take the example of calculator, lets consider that addition, subtraction, multiplication and
division are the modules whose functions are pre defined in the calculator and while we work,
we will call these modules.

The syntax to use the import statement is given below.

import module1,module2,........ module n


Use a Module
Now we can use the module we just created, by using the import statement:

Example

Import the module named firstmodule, and call the greeting function:

import mymodule

firstmodule.greeting("Raj")

Output

Hello Raj

Note: When using a function from a module, use the syntax: module_name.function_name.
Example:

# A simple module, calc.py

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)

# importing module calc.py


import calc

print add(10, 2)

Output:
12

The from-import statement

Instead of importing the whole module into the namespace, python provides the flexibility to
import only the specific attributes of a module. This can be done by using from-import
statement. The syntax to use the from-import statement is given below.

from < module-name> import <name 1>, <name 2>..,<name n>

# 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)

Output:
4.0
720

Consider the following module named as calculation which contains three functions as
summation, multiplication, and divide.

calculation.py:

1. #place the code in the calculation.py


2. def addition(a,b):
3. return a+b
4. def subtraction(a,b):
5. return a-b
6. def multiplication(a,b):
7. return a*b;
8. def divide(a,b):
9. return a/b;

Main.py:

1. from calculation import addition


2. #it will import only the addition() from calculation.py
3. a = int(input("Enter the first number"))
4. b = int(input("Enter the second number"))
5. print("Sum = ",addition(a,b)) #we do not need to specify the module name while accessing
addition()

Output:

Enter the first number10


Enter the second number20
Sum = 30
The from...import statement is always better to use if we know the attributes to be imported from
the module in advance. It doesn't let our code to be heavier. We can also import all the attributes
from a module by using *.

Consider the following syntax.

from <module> import *

Renaming a module

Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.

The syntax to rename a module is given below.

import <module-name> as <specific-name>

Example
1. #the module calculation of previous example is imported in this example as cal.
2. import calculation as cal;
3. a = int(input("Enter a:"));
4. b = int(input("Enter b:"));
5. print("Sum = ",cal.addition(a,b))

Output:

Enter a1:0
Enter b:20
Sum = 30
Python Classes/Objects
Python is an object oriented programming language. Almost everything in Python is an object,
with its properties and methods.

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 its
class) for modifying its state.

Class creates a user-defined data structure, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A class is like
a blueprint for an object.

Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
# Statement-N

Create a Class
To create a class, use the keyword class:

Example

Create a class named MyClass, with a property named x:

class MyClass:
x=5

Output

<class '__main__.MyClass'>

Class Objects

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the
class with actual values.
It’s not an idea anymore, it’s an actual snake. We can have many snakes to create many different
instances, but without the class ‘Snake’ as a guide, we would be lost, not knowing what
information is required.
An object consists of :
• State : It is represented by attributes of an object. It also reflects the properties of an object.
• Behavior : It is represented by methods of an object. It also reflects the response of an
object with other objects.
• Identity : It gives a unique name to an object and enables one object to interact with other
objects.

Best example for the class “Snake”

Identity
• Name of
Snake

Attributes
• Breed
• Color

Behavior
• Eat
• Bite

Create Object
Now we can use the class named MyClass to create objects:

Example

Create an object named p1, and print the value of x:

class MyClass:
x=5

p1 = MyClass()
print(p1.x)

Output

You might also like