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")
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]:
In [2]:
import itronix as i
i.student['name']
Out[2]:
In [3]:
i.function("keisha")
Built-in Module¶
In [5]:
import platform
x = platform.system()
print(x)
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))
we can also import module as¶
In [8]:
import itronix as i
print(i.fact(5))
print(i.sod(123))
Import particular function from module¶
In [9]:
from itronix import fact,sod
print(fact(5))
print(sod(123))
import all the functions from module¶
In [10]:
from itronix import *
print(fact(5))
print(sod(123))