Import keyword is one of Python Keyword. In this series of Python tutorial of beginners, we will learn why to use import and how we can use it, what is the syntax of import and example of import keyword.
What is import keyword in Python
Keyword import is used in Python to include the functionality of some Python module. As its name suggest that import is used to importing functionality which is written in some other module or program.
Syntax of import
import is very easy to use. just use keyword import at the beginning of the program to import functionality.
import moduleName
- import is name of keyword.
- moduleName is name of module which need to be import like math, tkinter etc.
Why to use import
If we are using the functionality or any method of some module but we didn’t import the required module, we will get error at compile time. Let’s understand this by taking example.
Python import keyword example
In one of our previous post of find Square root of a number in Python. we have used statement like
import math
. Suppose we didn’t import math module in that example then we will get error like
#Python import keyword example tup1=(4,9,16,25,36,49) for x in tup1 : print("Square root of",x,"is :",math.sqrt(x))
Output
NameError: name 'math' is not defined
- If we don’t import math module then program will throw error that particular module is not defined.
- Here math is module name in our case.
So, After adding import statement in above example, program will execute properly.
#Python import keyword example import math tup1=(4,9,16,25,36,49) for x in tup1 : print("Square root of",x,"is :",math.sqrt(x))
Output
Square root of 4 is : 2.0 Square root of 9 is : 3.0 Square root of 16 is : 4.0 Square root of 25 is : 5.0 Square root of 36 is : 6.0 Square root of 49 is : 7.0
Hence we saw that, if we want to use functionality or methods of some module then we have to import that module in our Python program.