Modules and Functions in Python

  • November 18, 2022
  • python
JOIN Clause
What exactly is a Python Module?

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.

Importing Modules in Python:

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, for example, place the following command at the top of the script.


import module

Creating a simple module:

# A simple module,
def mul(x, y):
    return (x*y)
def div(x, y):
    return (x/y)

Importing the module:

# importing module
import calc

print(calc.mul(10, 2))


Import all Names:

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.


Locating Python Modules:

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:

  • It begins by looking for the module in the current directory.
  • If the module is not found in the current directory, Python searches the shell variable PYTHONPATH. PYTHONPATH is an environment variable that contains a list of directories.
  • If that fails as well, Python checks the installation-dependent list of directories that was configured when Python was installed.

Note: also read about Python Variables

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

Leave a Reply

Your email address will not be published. Required fields are marked *