Modules and Functions in Python

  • November 18, 2022
  • python
conditional if else
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 calc.py, for example, place the following command at the top of the script.

Syntax:

import module
Example:

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
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.
print(sqrt(16))
print(factorial(6))

Output:

4.0
720
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.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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