Types of Modules in Python : Built-in & User-defined Python Modules (2024)

Last Updated on July 13, 2023 by Mayank Dham

Types of Modules in Python : Built-in & User-defined Python Modules (1)

Python modules are files that consist of statements and definitions. In the Python programming language, there exist two primary categories of modules: built-in modules provided by Python itself and user-defined modules created by programmers.

What are Python Modules?

Python modules serve multiple purposes, including code reuse and facilitating the development and maintenance of large programs. They offer a means to separate implementation details from the main program, resulting in improved code readability and modifiability. By utilizing modules, developers can effectively organize and manage their code, promoting reusability and enhancing the overall efficiency of the programming process.

Python Modules can contain functions, classes, variables, and other objects, and can be imported into other programs to be used. The definitions and statements in a module can be accessed by other programs by using the import statement, followed by the name of the module. Python also provides several built-in modules that are always available for use, and users can create their own modules by saving their functions and variables in a file with a .py extension.

Now, let’s see what python modules look like with an example:

# user.pydef login(username): return "Welcome, " + username + "!"def logout(username): return "Have a nice day, " + username + "!"

Here we have created a python module user.py with two functions login and logout. Let’s see how we can use the above module in other programs.

# main.pyimport userprint(user.login("PrepBytes"))print(user.logout("PrepBytes"))

In the above code, we have imported the module user using the import keyword. After that, we used both the functions of the user module.

Output:

Welcome, PrepBytes!Have a nice day, PrepBytes!

Types of Python Modules

There are two types of python modules:

  • Built-in python modules
  • User-defined python modules

1. Built-in modules:

Python boasts an extensive collection of built-in modules designed to simplify tasks and enhance code readability. These modules offer a diverse range of functionality and are readily accessible without the requirement of installing extra packages. With these built-in modules, Python provides a comprehensive set of tools and capabilities right out of the box, allowing developers to accomplish various tasks conveniently and without the hassle of additional installations.

A list of a few most frequently used built-in python modules is given below

  • math: This module is very useful to perform complex mathematical functions such as trigonometric functions and logarithmic functions.
  • date: The date module can be used to work with date and time such as time, date, and datetime.
  • os: Provides a way to interact with the underlying operating system, such as reading or writing files, executing shell commands, and working with directories.
  • sys: Provides access to some variables used or maintained by the Python interpreter, such as the command-line arguments passed to the script, the Python version, and the location of the Python executable.

Example of built-in python modules.

  • Python
# Example using the os moduleimport osprint(os.getcwd())print(os.listdir())# Example using the sys moduleimport sysprint(sys.version)print(sys.argv)# Example using the math moduleimport mathprint(math.pi)print(math.sin(math.pi / 2))# Example using the json moduleimport jsondata = { "name": "John Doe", "age": 30, "city": "New York"}json_data = json.dumps(data)print(json_data)# Example using the datetime moduleimport datetimenow = datetime.datetime.now()print(now)print(now.year)print(now.month)print(now.day)# Example using the re moduleimport retext = "The quick brown fox jumps over the lazy dog."result = re.search(r"fox", text)print(result.start(), result.end(), result[0])# Example using the random moduleimport randomprint(random.randint(1, 100))print(random.choice([1, 2, 3, 4, 5]))

Output:

/home/bEO6qL['prog']3.9.5 (default, Nov 18 2021, 16:00:48) [GCC 10.3.0]['./prog']3.1415926535897931.0{"name": "John Doe", "age": 30, "city": "New York"}2023-02-06 11:21:49.35487320232616 19 fox17

5

2. User-defined modules in Python:

User-defined python modules are the modules, which are created by the user to simplify their project. These modules can contain functions, classes, variables, and other code that you can reuse across multiple scripts.

How to create a user-defined module?

We will create a module calculator to perform basic mathematical operations.

# calculator.pydef add(a, b): return a + bdef sub(a, b): return a - bdef mul(a, b): return a * bdef div(a, b): return a / b

In the above code, we have implemented basic mathematic operations. After that, we will save the above python file as calculator.py.

Now, we will use the above user-defined python module in another python program.

# main.pyimport calculatorprint("Addition of 5 and 4 is:", calculator.add(5, 4))print("Subtraction of 7 and 2 is:", calculator.sub(7, 2))print("Multiplication of 3 and 4 is:", calculator.mul(3, 4))print("Division of 12 and 3 is:", calculator.div(12, 3))

Output:

Addition of 5 and 4 is: 9Subtraction of 7 and 2 is: 5Multiplication of 3 and 4 is: 12Division of 12 and 3 is: 4.0

How to import python modules?

We can import python modules using keyword import. The syntax to import python modules is given below.

Syntax to Import Python Modules

import module_name

Example to Import Python Modules:

import mathprint(math.sqrt(4))

Output:

2.0

In the above program, we imported all the attributes of module math and we used the sqrt function of that module.

Now, let’s see how we can import specific attributes from the python module.

To import specific attributes or functions from a particular module we can use keywords from along with import.

Syntax to import python module using Attribute:

from module_name import attribute_name

Example of import python module using Attribute:

from math import sqrtprint(sqrt(4))

Output:

2.0

Now, let’s see how we can import all the attributes or functions from the module at the same time.

We can import all the attributes or functions from the module at the same time using the * sign.

Syntax to import python module using all Attributes:

from module_name import *

Example to import python module using all Attributes:

from math import *print(sqrt(4))print(log2(8))

Output:

2.03.0

Conclusion
In conclusion, Python modules are instrumental in code reuse, program organization, and enhancing the functionality of Python programs. They enable developers to separate implementation details, improve code readability, and maintain large-scale projects effectively. With a vast collection of built-in modules, Python provides a rich ecosystem of functionalities, making it easier to accomplish a wide range of tasks without the need for additional package installations.

FAQs Related to Python Modules

1. What are the different types of Python modules?
There are two main types of Python modules: built-in modules and user-defined modules. Built-in modules are modules that come preinstalled with Python, while user-defined modules are modules that you create yourself.

2. Can you import multiple modules into a Python script at once?
Yes, you can import multiple modules into a Python script by using multiple import statements. For example, you can write import module1, module2, module3 to import three modules at once.

3. Can we rename a module when you import it into a Python script?
Yes, you can rename a module when you import it into a Python script by using the as the keyword. For example, you can write import module1 as m1 to import the module1 module under the name m1.

4. Can we only import specific functions or classes from a module in Python?
Yes, you can import specific functions or classes from a module in Python by using the from keyword. For example, you can write from module1 import function1 to import the function1 function from the module1 module.

5. What happens if two modules have a function or class with the same name?
If two modules have a function or class with the same name, you need to qualify the names of the functions or classes from each module to avoid ambiguity. For example, if both module1 and module2 have a function named function1, you would write module1.function1() and module2.function1() to call the functions from each module, respectively.

6. Can you import a module that is in a different directory in Python?
Yes, you can import a module that is in a different directory in Python by adding the directory to the sys.path list. This will make Python look in the specified directory for modules when you run an import statement.

7. Can you import a module from the Internet in Python?
Yes, you can import a module from the Internet in Python by using a package manager, such as pip, to install the package that contains the module. Once the package is installed, you can import the module in your script just like any other module.

Types of Modules in Python : Built-in & User-defined Python Modules (2024)
Top Articles
ICICI Bank Fixed Deposit
Send money to a Bitcoin address with Skrill 
NOAA: National Oceanic & Atmospheric Administration hiring NOAA Commissioned Officer: Inter-Service Transfer in Spokane Valley, WA | LinkedIn
#ridwork guides | fountainpenguin
Craigslist In South Carolina - Craigslist Near You
Www Craigslist Louisville
Palace Pizza Joplin
Does Pappadeaux Pay Weekly
Aita Autism
Revitalising marine ecosystems: D-Shape’s innovative 3D-printed reef restoration solution - StartmeupHK
Bros Movie Wiki
Cvs Learnet Modules
Gfs Rivergate
Enderal:Ausrüstung – Sureai
Rosemary Beach, Panama City Beach, FL Real Estate & Homes for Sale | realtor.com®
The Witcher 3 Wild Hunt: Map of important locations M19
Luna Lola: The Moon Wolf book by Park Kara
Overton Funeral Home Waterloo Iowa
Les Schwab Product Code Lookup
Inside the life of 17-year-old Charli D'Amelio, the most popular TikTok star in the world who now has her own TV show and clothing line
St Maries Idaho Craigslist
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
U Of Arizona Phonebook
Air Quality Index Endicott Ny
Il Speedtest Rcn Net
Hdmovie2 Sbs
Geico Car Insurance Review 2024
Giantbodybuilder.com
NV Energy issues outage watch for South Carson City, Genoa and Glenbrook
UPC Code Lookup: Free UPC Code Lookup With Major Retailers
Warn Notice Va
Grandstand 13 Fenway
O'reilly Auto Parts Ozark Distribution Center Stockton Photos
Deleted app while troubleshooting recent outage, can I get my devices back?
Watchseries To New Domain
Pp503063
Cheetah Pitbull For Sale
Cal Poly 2027 College Confidential
Craigslist Malone New York
Homeloanserv Account Login
Satucket Lectionary
Atu Bookstore Ozark
Swoop Amazon S3
Copd Active Learning Template
Youravon Com Mi Cuenta
Gw2 Support Specter
552 Bus Schedule To Atlantic City
Diario Las Americas Rentas Hialeah
Black Adam Showtimes Near Kerasotes Showplace 14
Rise Meadville Reviews
Mazda 3 Depreciation
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 6426

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.