Python import keyword or statement

The import keyword or statement in Python is used when we need to import or load modules in a program.

A module is a collection of Python code that can be used to do specific tasks or add features that aren't in the standard library. By importing a module, you can use the functions, classes, and variables it defines in your program.

In Python, you use the "import" statement followed by the name of the module you want to use. To import the "math" module, for example, you should type:

import math

This will import the whole "math" module, which has a lot of functions and constants for math.

Once you've imported the module, you can use the dot notation to access its functions and variables. To use the "sqrt" function from the "math" module, for example, write:

import math

x = math.sqrt(49)
print(x)

The output should be:

7

The "from" keyword can also be used to import functions or variables from a module. Consider the following code as an example:

from math import sqrt

Now, your program will only import the "sqrt" function from the "math" module. Other "math" module functions, classes, and variables will be inaccessible in the program.

Python import statement example

The following program is another example of a Python statement or keyword called "import."

import datetime

print(datetime.datetime.today())

The sample output of this program is:

2021-12-20 08:39:51.731020

The import keyword is used in the above program to import the datetime module to print the current date and time.

However, you might get a different result. I got this output because, while running the above program, the current date and time in my system were the ones shown above. You will receive a different one depending on the date you run the program.

HHere's another program that shows how to use import to load a module into a program. This program uses import to load a random module:

import random

print(random.random())

The sample output is:

0.20462596685802914

Every time you execute the program, you'll get a different random number.

You can import not only modules from the standard library, but also modules that you have made or that other developers have made. To import a module that isn't in the standard library, make sure it's installed on your system or in the same directory as your Python script.

Use the "as" keyword to give a module an alias. For example:

import numpy as np

Now you can use "np" (a short name) instead of "numpy" (the full module name) in your program.

To summarize, the "import" statement is an essential part of working with Python modules. You can use the "import" statement to access and use functions, classes, and variables defined in a module in your program. You can also import specific functions or variables from a module, give a module an alias, and import modules that you created or that other developers created.

Python Online Test


« Previous Tutorial Next Tutorial »