A module in Python is a file that contains functions, variables, and classes which you can reuse in another Python program. Importing modules helps you avoid rewriting code and use built-in or external functionality.


1️⃣ Importing an Entire Module

Use the import keyword.

import math

print(math.sqrt(16))
print(math.pi)

βœ… Output:

4.0
3.141592653589793

Here:

  • math β†’ module name
  • sqrt() and pi β†’ used with math. prefix

2️⃣ Import Specific Functions from a Module

You can import only the parts you need.

from math import sqrt, pi

print(sqrt(25))
print(pi)

Now you don’t need the module prefix.


3️⃣ Import with an Alias (Shortcut Name)

Use as to give a module a shorter name.

import math as m

print(m.sqrt(36))

Common example:

import numpy as np

4️⃣ Import Everything from a Module

from math import *

print(sqrt(49))
print(pi)

⚠️ Not recommended in large programs because it may create name conflicts.


5️⃣ Import Your Own Module

If you create a file:

mymodule.py

def greet(name):
print("Hello", name)

Then in another file:

import mymodule

mymodule.greet("Venkat")

6️⃣ Example with Built-in Module

Using the random module:

import randomprint(random.randint(1, 10))

This generates a random number between 1 and 10.


πŸ“Š Summary

SyntaxMeaning
import moduleImport entire module
from module import nameImport specific function
import module as aliasImport with shortcut
from module import *Import everything

βœ… Simple Tip:
Most Python programs commonly import modules like:

import math
import random
import datetime