Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Arrays
Next article icon

Python Module is a file that contains built-in functions, classes,its and variables. There are manyPython modules, each with its specific work.

In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we can use the alias to rename the module, etc.

What is Python Module

APythonmodule is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code.

Grouping related code into a module makes the code easier to understand and use. It also makes the code logically organized.

Create a Python Module

To create a Python module, write the desired code and save that in a file with .pyextension. Let's understand it better with an example:

Example:

Let's create a simple calc.py in which we define two functions, oneadd and anothersubtract.

Python
# A simple module, calc.pydefadd(x,y):return(x+y)defsubtract(x,y):return(x-y)

Import module in Python

We can import the functions, and classes defined in a module to another module using theimport statement in some other Python source file.

When the interpreter encounters an import statement, it imports the module if the module is present in the search path.

Note: A search path is a list of directories that the interpreter searches for importing a module.

For example, to import the module calc.py, we need to put the following command at the top of the script.

Syntax to Import Module in Python

import module

Note:This does not import the functions or classes directly instead imports the module only. To access the functions inside the module the dot(.) operator is used.

Importing modules in Python Example

Now, we are importing thecalc that we created earlier to perform add operation.

Python
# importing  module calc.pyimportcalcprint(calc.add(10,2))

Output:

12

Python Import From Module

Python's from statement lets you import specific attributes from a module without importing the module as a whole.

Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the math module.

Python
# importing sqrt() and factorial from the# module mathfrommathimportsqrt,factorial# if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))

Output: 

4.0
720

Import all Names 

The * symbol used with the import statement is used to import all the names from a module to a current namespace.

Syntax:

from module_name import *

What does import * do in Python?

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module, it is not recommended to use *, else do so.

Python
# importing sqrt() and factorial from the# module mathfrommathimport*# if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(sqrt(16))print(factorial(6))

Output

4.0
720

Locating Python Modules

Whenever a module is imported in Python the interpreter looks for several locations. First, it will check for thebuilt-in module, if not found then it looks for a list of directories defined in thesys.path. Python interpreter searches for the module in the following manner -

  • First, it searches for the module in the current directory.
  • If the module isn’t found in the current directory, Python then searches each directory in the shell variablePYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of directories.
  • If that also fails python checks the installation-dependent list of directories configured at the time Python is installed.

Directories List for Modules

Here, sys.path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search for the required module.

Python
# importing sys moduleimportsys# importing sys.pathprint(sys.path)

Output:

['/home/nikhil/Desktop/gfg', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '', '/home/nikhil/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages', '/usr/local/lib/python3.8/dist-packages/IPython/extensions', '/home/nikhil/.ipython']

Renaming the Python Module

We can rename the module while importing it using the keyword.

Syntax:  ImportModule_name asAlias_name

Python
# importing sqrt() and factorial from the# module mathimportmathasmt# if we simply do "import math", then# math.sqrt(16) and math.factorial()# are required.print(mt.sqrt(16))print(mt.factorial(6))

Output
4.0720

Python Built-in modules

There are several built-in modules in Python, which you can import whenever you like.

Python
# importing built-in module mathimportmath# using square root(sqrt) function contained# in math moduleprint(math.sqrt(25))# using pi function contained in math moduleprint(math.pi)# 2 radians = 114.59 degreesprint(math.degrees(2))# 60 degrees = 1.04 radiansprint(math.radians(60))# Sine of 2 radiansprint(math.sin(2))# Cosine of 0.5 radiansprint(math.cos(0.5))# Tangent of 0.23 radiansprint(math.tan(0.23))# 1 * 2 * 3 * 4 = 24print(math.factorial(4))# importing built in module randomimportrandom# printing random integer between 0 and 5print(random.randint(0,5))# print random floating point number between 0 and 1print(random.random())# random number between 0 and 100print(random.random()*100)List=[1,4,True,800,"python",27,"hello"]# using choice function in random module for choosing# a random element from a set such as a listprint(random.choice(List))# importing built in module datetimeimportdatetimefromdatetimeimportdateimporttime# Returns the number of seconds since the# Unix Epoch, January 1st 1970print(time.time())# Converts a number of seconds to a date objectprint(date.fromtimestamp(454554))

Output:

5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87

We have covered Python Modules and it's operations like create, import, etc. This article will give the overview about Python modules so that you can easily create and use modules in Python.

Also Read:


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp