Python modules are files that contain Python definitions and statements. Functions, classes, and variables can all be defined by a module. A module may also contain executable code. Grouping related code into modules makes it easier to understand and use the code. It also helps to organize the code logically.
Using the import statement in another Python source file, we can import the functions and classes defined in one module into another.
When the interpreter comes across an import statement, it imports the module if it is in the search path. A search path is a directory list that the interpreter looks through when importing a module. To import the module calc.py, for example, place the following command at the top of the script.
Syntax:
import module
Creating a simple module:
# A simple module, cal.py
def mul(x, y):
return (x*y)
def div(x, y):
return (x/y)
Importing the cal.py module:
# importing module cal.py
import calc
print(calc.mul(10, 2))
Output:
20
The import statement’s * symbol is used to import all the names from a module into the current namespace.
for instance,
from math import *
# 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
When a module is imported into Python, the interpreter looks in several places. It will first look for the built-in module, and if it is not found, it will look for a list of directories defined in the sys.path. The Python interpreter looks for the module in the following way:
Note: also read about Python Variables
Please follow me to read my latest post on programming and technology if you like my post.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…