How to import module in Python | Example code

By importing the module you can get access to code from another module in Python. Just use the import statement to import any module in python.

How to import modules in Python?

The python module is nothing but a code of variables, functions, or class defined. This filename becomes the module name. Users can define a module or can use inbuild modules like math modules.

To use the module, you have to import it using the import keyword. Let’s see examples for it:-

Import inbuild python math moudles

import math

# Square root of number
sqrValue = math.sqrt(25)
print(sqrValue)

Output: 5.0

Custome module import example

main.py

var = "Hello main file"
num = 9876543210


def greeting(name):
    print("Hello, " + name)

Test.py

import main

main.greeting("John")
print(main.num)

Output:

Hello, John
9876543210

How to import module in Python

Read more ways to import module:- Python import variable from another file

Do comment if you have any doubts and suggestions on this Python module tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.