Saturday , December 21 2024
Python Modules - Create Own Custom Modules in Python

Python Modules

Python Modules

What is a Module?

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.

Create a Module

  • To create a module just save the code you want in a file with the file extension .py:
In [1]:
#Save this code in itronix.py file
def function(name):
    print("Hello, " + name)

Note: Save this code in a file named itronix.py

  • Import the module named itronix, and call the function:
In [2]:
import itronix
itronix.function("Karan")
Hello, Karan

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

Variables in Module

  • Import the module named itronix, and access the student dictionary:
In [3]:
#Save this code in itronix.py file
student = {
  "name": "Keisha",
  "age": 26,
  "country": "India"
}
In [1]:
import itronix
itronix.student['name']
Out[1]:
'Keisha'

Naming a Module

  • You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

  • You can create an alias when you import a module, by using the as keyword:
In [2]:
import itronix as i
i.student['name']
Out[2]:
'Keisha'
In [3]:
i.function("keisha")
Hello, keisha

Built-in Module

In [5]:
import platform

x = platform.system()
print(x)
Windows

Here, we define two functions factorial and sum of digit in same module itronix.py

In [6]:
def fact(n):
    f=1
    for i in range(1,n+1):
        f=f*i
    return f

def sod(n):
    mod=0
    while(n!=0):
        m=n%10
        n=n//10
        mod=mod+m
    return mod
In [7]:
import itronix
print(itronix.fact(5))
print(itronix.sod(123))
120
6

we can also import module as

In [8]:
import itronix as i
print(i.fact(5))
print(i.sod(123))
120
6

Import particular function from module

In [9]:
from itronix import fact,sod
print(fact(5))
print(sod(123))
120
6

import all the functions from module

In [10]:
from itronix import *
print(fact(5))
print(sod(123))
120
6

About Machine Learning

Check Also

Python MySQL Insert Into Table

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *