Modules in Python

Day 13 in #100DaysOfCode

Modules in Python

We use modules to organize our code into multiple files. We refer to each file as a module. Modules in Python are simple files with the ".py" suffix that contain Python code that may be imported into another Python program.

How Do You Make Python Modules?

To construct a module, we must store the desired code in a file with the file extension ".py." The name of the Python file is then used as the name of the module.

Example: I created a new .py file named "new file.py" and wrote this code in it:

books = {
  "book": "Dune",
  "date": 1965,
  "author": "Frank Herbert"
}

Then, I went back to my original page which was called app.py. I have typed this code here to import from newfile.py.

import newfile
a = newfile.books["book"]
b = newfile.books["author"]

print(a,"is written by", b)

Result:

Dune is written by Frank Herbert

Modules' Benefits

Some of the benefits of working with modules in Python are as follows:

Reusability

Working with modules allows the code to be reused.

Simplicity

The module concentrates on a subset of the problem rather than the complete topic.

Scoping

A distinct namespace is specified by a module, which aids in avoiding identifier clashes.