Python From Beginner to Advanced

0% completed

Previous
Next
Python - Basics of Modules

A module in Python is a file that contains Python functions, classes, and variables that can be reused across different programs. Instead of writing the same code repeatedly, you can define it once in a module and import it wherever needed.

Using modules makes Python programs organized, reusable, and easier to manage. Python provides:

  • Built-in Modules (e.g., math, random, os)
  • User-Defined Modules (custom Python files created by users)

Modules help in code reusability, better structure, and easier debugging by breaking large programs into smaller, manageable parts.

1. Creating and Using a Module

A module is simply a Python file (.py) that contains functions and variables. To use a module, we import it using the import statement.

Example 1: Creating a Module

Create a file called my_module.py with the following content:

Python3
Python3
. . . .

Now, you can import and use this module in another script.

2. Importing a Module in Python

To use the module, import it in another Python script.

Example 2: Importing a Module in Another File

Python3
Python3
. . . .

Explanation:

  • import my_module loads all functions and variables from my_module.py.
  • my_module.greet("Alice") calls the greet() function from the module.
  • my_module.PI accesses the PI variable from the module.

3. Importing Specific Items from a Module

Instead of importing the entire module, you can import only specific functions or variables.

Example 3: Importing Specific Functions from a Module

Python3
Python3
. . . .

Explanation:

  • from my_module import greet imports only the greet function.
  • No need to use my_module.greet(), you can call greet() directly.

4. Using Aliases for Modules and Functions

You can use aliases (as) to rename modules or functions when importing.

Example 4: Using Aliases for Modules

Python3
Python3
. . . .

Example 5: Using Aliases for Functions

Python3
Python3
. . . .

Explanation:

  • import my_module as mm allows using mm.greet() instead of my_module.greet().
  • from my_module import greet as hello renames greet() to hello().

5. Finding Available Functions in a Module

Use the dir() function to list all functions and variables available in a module.

Example 6: Listing Module Functions

Python3
Python3
. . . .

Explanation:

  • dir(my_module) displays a list of all functions, variables, and attributes inside my_module.

Modules make Python programs efficient, reusable, and organized by separating code into manageable files.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next