Skip to main content

1. What is a Module?

A module is a Python file (.py) that contains functions, variables, or classes that can be reused in other Python programs. Example:
You can import and use it in another file:
Output:

Advantages of Modules

  • Code reusability
  • Better organization
  • Easier debugging
  • Avoid code duplication
  • Makes projects easier to maintain

2. Importing Built-in Modules

Python provides many built-in modules that come with the language.

Example: math

Output
Common functions:

Example: random

Generates a random integer between 1 and 10.

Example: datetime

Shows the current date and time.

3. Different Ways to Import Modules

a) Import entire module


b) Import specific function


c) Import multiple functions


d) Import with alias

Alias (m) is a shorter name.
Avoid this in large projects because it can create naming conflicts.

4. Third-Party Modules

Third-party modules are created by other developers and installed using pip.

Install


Example


Some popular third-party modules:

5. Creating Your Own Module (utils.py)

Suppose you have a file named:
Contents:

Another file:
Output

Import specific function


Alias