Skip to main content

What is Python Modules ? Built-in, User-Defined Modules with Examples:

 

✍️Introduction

A module in Python is a file that contains functions, variables, and classes.
Modules help us organize code, reuse functionality, and keep programs clean.

Modules in Python allow developers to break large programs into smaller, manageable parts, making code easier to maintain and understand.

Any Python file with .py extension is a module.


Why Use Modules?

Modules are used to make programs reusable, well-organized, easy to maintain, and faster to develop by grouping related code together:
  • Code reusability

  • Better organization

  • Easy maintenance

  • Faster development


Types of Python Modules ?

Python modules are classified into built-in modules provided by Python, user-defined modules created by programmers, and third-party modules developed by external contributors.
  1. Built-in Modules

  2. User-Defined Modules

  3. Third-Party Modules


1️⃣ Built-in Modules:

Python provides many built-in modules.

Built-in modules are pre-installed Python modules that provide ready-to-use functions, such as the math module for mathematical operations.

Example 1: math Module

import math print(math.sqrt(16))

Output:
4.0

"Code executed successfully" 

The random module is a built-in Python module used to generate random numbers and perform random selections.

Example 2: random Module

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

Output:
10

"Code executed successfully" 

Common Built-in Modules:

Module                       Use
mathMathematical operations
random    Random numbers
datetimeDate & time
osOperating system
sysSystem operations

2️⃣ User-Defined Module:

A user-defined module is a Python file created by the programmer to store reusable functions and variables that can be imported and used in other programs.

# Step 1: Create Module (mymodule.py)

def greet(name): print("Hello", name) pi = 3.14

# Step 2: Use Module

import mymodule mymodule.greet("Python") print(mymodule.pi)


Output:
Hello Python 3.14

"Code executed successfully" 

Different ways to import modules:

Python provides multiple ways to import modules so that programmers can access required functions efficiently and write cleaner, more readable code.

Import entire module:

(import math Gives access to all functions using the module name, which avoids name conflicts.

Import specific functions:

(from math import sqrt Imports only required functions, making the code shorter and slightly faster.
from math import sqrt

Import with alias:

(import math as mAssigns a shorter name to the module, improving code readability and convenience.


dir() Function:

The dir() function is used to display all the available functions, variables, and attributes present in a module.

Example:

import math print(dir(math))

Output:

['__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil',
'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist',
'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf',
'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10',
'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi',
'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh',
'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']

"Code executed successfully" 

__name__ == "__main__":

__name__ == "__main__" is a special condition in Python used to check whether a program is executed directly or imported as a module.

Used to check whether the module is run directly.

Example:

if __name__ == "__main__": print("Program executed directly")

Output:
Program executed directly

"Code executed successfully" 

3️⃣ Third-Party Modules

Third-party modules are external Python libraries developed by others that are not included with Python and must be installed separately using pip.

These modules extend Python’s capabilities by providing advanced features such as numerical computing, data analysis, machine learning, and web development.
For example, numpy is a popular third-party module used for efficient mathematical and array operations.

Simple Installation Process:


Third-party modules are installed using pip.
Open the command prompt or terminal and run pip install module_name 

(for example, pip install numpy), 

then import it in your program using import module_name

(for example, import numpy).

Note:PIP is a package manager for Python packages, or modules


Module vs Package:

Module            Package           
Single file Folder of modules
.py file Contains __init__.py
Simple                 Large project

❌ Common Mistakes:

  • Wrong module name

  • Forgetting .py extension

  • Not installing third-party module


📌Interview Questions ?

1️⃣ What is a module?

Ans:
A module is a Python file that contains functions, variables, and classes which can be reused in other programs.

2️⃣ Difference between module and package:

Ans:
A module is a single Python file, whereas a package is a collection of related modules organized inside a directory.

3️⃣ What is __main__?

Ans:
__main__ is the name given to the Python file that is executed directly, used to control which code runs on direct execution.

Conclusion:

Python modules help in writing clean, reusable, and professional code.
They are essential for large applications and projects.


💬 Quick Question

What will be the output?

import math print(math.ceil(4.2))

Comment your answer 👇😊


📌 Related Articles

Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type