Python Mod & Pac
Python Mod & Pac
&PACKAGES
MODULES
CREATING A MODULE
USING A MODULE
NAMING A MODULE
BUILT-IN MODULES
PACKAGES
STRUCTURE OF PACKAGES
DIFFERENCE B/W MODULES &PACKAGES
WHAT IS MODULES:
A file containing definitions of functions and
various statements is called a python module.
TYPES:
1. Built-in module
2. User-defined module
CREATING A MODULE
To create a module just save the code you want in a file with
the file extension .Py:
EXAMPLE:
get your own python server save this code in a file
named mymodule.Py
def greeting(name):
print("hello, " + name)
USING A MODULE:
Now we can use the module we just created, by using the import
statement:
EXAMPLE:
Import the module named mymodule, and call the
greeting function:
import mymodule
mymodule.greeting(“Prithi")
NAMING A MODULE:
You can name the module file whatever you like, but it must
have the file extension .py.You can create an alias when you import
a module.
Example:
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.greeting(“Nila”)
print(a)
IMPORT FROM MODULE:
You can choose to import only parts from a module, by
using the from keyword.
Example:
def add(a,b):
c=a+b
print("addition of ",a," &", b, "is", c)
def multiple(a,b):
c=a*b
print("multiple of ",a," &", b, "is", c)
Example:
Import only the person1 dictionary from the module:
from mymodule1 import add
a=int(input("enter A value:"))
b=int(input("enter B value:"))
x=add(a,b)
Note: When importing using the from keyword, do not use the
module name when referring to elements in the module.
Built –in module:
PYTHON DATES:
A date in Python is not a data type of its own, but we
can import a module named datetime to work with dates as date
objects.
Example:
Get your own Python Server Import the datetime module
and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
The datetime module has many methods to return
information about the date object.
Here are a few examples, you will learn more about them later
in this chapter:
Example1:
Return the year and name of weekday:
import datetime
x =datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Example2:
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)