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
How Time Travel Works
Best Crypto Bridges for Cross-Chain
Woodward Avenue (M-1) - Automotive Heritage Trail - National Scenic Byway Foundation
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
Noaa Charleston Wv
Lamb Funeral Home Obituaries Columbus Ga
Craigslist Vans
Craigslist Benton Harbor Michigan
Jefferey Dahmer Autopsy Photos
From Algeria to Uzbekistan-These Are the Top Baby Names Around the World
Gabrielle Abbate Obituary
Myhr North Memorial
Kostenlose Games: Die besten Free to play Spiele 2024 - Update mit einem legendären Shooter
A Guide to Common New England Home Styles
O'reilly's Auto Parts Closest To My Location
Gmail Psu
National Weather Service Denver Co Forecast
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Chastity Brainwash
Urban Dictionary: hungolomghononoloughongous
Palm Coast Permits Online
Spergo Net Worth 2022
U Arizona Phonebook
Labby Memorial Funeral Homes Leesville Obituaries
Missed Connections Inland Empire
Team C Lakewood
Used Safari Condo Alto R1723 For Sale
Surplus property Definition: 397 Samples | Law Insider
Jcp Meevo Com
Bidrl.com Visalia
'Insidious: The Red Door': Release Date, Cast, Trailer, and What to Expect
Aes Salt Lake City Showdown
Tamil Movies - Ogomovies
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Frommer's Belgium, Holland and Luxembourg (Frommer's Complete Guides) - PDF Free Download
Vistatech Quadcopter Drone With Camera Reviews
Greencastle Railcam
Senior Houses For Sale Near Me
Leatherwall Ll Classifieds
Dynavax Technologies Corp (DVAX)
Los Garroberros Menu
Gary Lezak Annual Salary
The All-New MyUMobile App - Support | U Mobile
Wilson Tattoo Shops
Online-Reservierungen - Booqable Vermietungssoftware
VerTRIO Comfort MHR 1800 - 3 Standen Elektrische Kachel - Hoog Capaciteit Carbon... | bol
2294141287
Motorcycles for Sale on Craigslist: The Ultimate Guide - First Republic Craigslist
Fine Taladorian Cheese Platter
Wrentham Outlets Hours Sunday
Emmi-Sellers
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.