Imports in Python
Python import statement is used to import modules that we want to use in our program.
At the point when our program develops greater, it is a smart thought to break it into various modules.
A module is a file containing Python definitions and explanations. Python modules have a filename and end with the extension .py.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.
Python imports are case sensitive, so import math and import Math are completely two different modules.
Let us see the built-in modules in Python.
For instance, we can import the math and sys module by typing the accompanying line:
import math import sys
To use the math module we need to do the following:
import math print(math.pi)
Presently all the definitions inside the math modules are accessible in our scope. We can likewise import some particular attributes and functions just, using the from keyword. For instance:
from math import pi pi
Python import user-defined module
Similarly, we can create our own module with the extension .py. We can use our created module in our program by using import statements.
def sub(x, jy): return int(x) - int(y) def add(a,b): return int(a) + int(b)
Save the code in a file named newimport.py and then execute the following
import newimport print("sub=",newimport.sub(10,10)) print("add=",newimport.add(20,30))
Python import as
We can define our own name for the imported module using import as a statement
Let us understand with the help of an example:
def name(name): print("Welcome "+ name)
Save the code in a file named newimport.py
import newimport as ni ni.name("John")
Python import from a module
You can choose to import only parts from a module, by using the from keyword.
def sub(i, j): return int(i) - int(j) def name(name): print("Welcome "+ name) def add(a,b): return int(a) + int(b)
So, suppose we want to import only the sub-function, the code should be as follows:
from newimport import sub print("sub=",sub(40,10))
Using dir() function
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
import random print("Random directories are:") print(dir(random))