Packages in Python and Using Python Module Index
Day 14 in #100DaysOfCode
#2Articles1Week
Packages
Packages are another way to organize our code. The package is a container for multiple modules. A package is essentially a directory containing Python files and a file called init .py. This implies that Python will regard any directory inside the Python path that has a file named init .py as a package. It is possible to include many modules in a Package.
PS: Packages are extremely important in Django.
In order for Python to recognize a directory as a package, it must have a file named init .py. This file can be left empty, although we usually put the package's startup code in here.
Here is an example of how this works:
Python Module Index
There are so many modules that are already built-in with Python. And we can reuse them for our own code.
So how do we find a standard library?
1- Open up your browser and type "python 3 module index". 2- As it appears in the first line go to "docs.python.org/3/py-modindex.html" 3- There are already built-in modules that can be used in Python.
We can have an example of how to implement one of these modules listed in the web page:
Example: Generating Random Modules in Python
Python knows the "random" module and it also knows where to find it.
Now we want to generate random values by also using "range". With this, we will be able to generate random values between 0 and 1.
import random
for i in range(5):
print(random.random())
And result will look like this:
0.2916596938667211
0.6736630110428875
0.2663239683456571
0.8880752855418649
0.0725170327105702
Process finished with exit code 0
Now, let us have another example:
Imagine you have a lot of movies to watch on your list but you are not sure which one to watch. With the same "random" module we can help you pick one.
import random
movies=['Mission Impossible', 'LOTR', 'Avangers', 'Dune']
watch_this=random.choice(movies)
print(watch_this)
And result will look like this:
LOTR
Process finished with exit code 0
Process finished with exit code 0
Each time we run the code, our movie choice will change.