The Python Import is statements are similar to the
#include statements in C/C++ but different. It allows you to use functions defined elsewhere either in a standard module or package or your own modules. In this tutorial, you will learn about Python Import statements in detail with examples.
If you know some of the imported manners in another programming language, you will find in the code calls to functions of this kind
< module_name >.< function >, Some of the import standard modules are in python is :
import getopt import os import re import string import sys import getpass import urllib import subprocess
Why Python Import Module?
Because if you need any functionality in your app you need to write a code , for that you have to depend on other codes. That Time you need to import those module (like libraries) or package and use it.
Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.
For example, the module
sys allows you to do this:
import sys #down if something sys.exit(0)
It will terminate the program, you don’t have to write any code for the
exit()function, it’s defined within the standard
Import is searches for the module initially in the local scope by
calling __import__() function. The value returned by the function are then reflected in the output of the initial code.
This is an example of factorial in python, using a factorial function of standard math module.
import math print(math.factorial(5))
Output : 120
fsum as a whole can be imported into our initial code, rather than importing the whole module.
from math import fsum print(fsum([1, 2, 3, 1]))
Output : 7.0
module_name import *
All the functions and constants can be imported using *.
See this example not suing the math module, because all important to direct use.
from math import * print(fsum([1, 2, 3, 1])) print(factorial(5))
Output : 7.0
Bonus: What is Modules and How to create is must follow this tutorial: Python Modules Custom and Builtin.
Do comment if you have any doubts and suggestions on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python Import-Module Examples are in Python 3, so it may change its different from python 2 or upgraded versions.