Python Modules
Python Modules
Python modules are python files that contain python code that we can use within our python files ensuring simplicity and code reusability.
Here are some popular python built-in modules:
csv, datetime, json, math, random, sqlite3, statistics, tkinter, turtle, etc.
Example: importing math module:
Output:
Apart from this we can create our own modules and use them within other python files.
A. Creating and using module:
Write code and save file with extension .py .
Example: creating file module.py and writing some code:
Now we can use this code in a different python file by simply using the import statement.
Example: creating file calc.py and importing module.py
Now we can write code to call the functions from module.py in calc.py
Example:
Output:
B. Using an alias:
We can also use alias while importing module. This way we do not need to write the whole name of the module while calling it.
Example:
Output:
C. import from module:
You can also import specific parts that you need from a module instead of importing the entire module.
Example: creating file module.py and writing some code:
Example: now we will only import add() and sub() function into our calc.py file.
Output:
As we can see that, we have only imported add() and sub() functions from module.py file. Hence we get output for these functions, but we get error if we use any other functions.
But what if want to import everything from a module but we do not need to prefix module name again and again?
Use an asterisk(*) while importing.
Example:
Output:
As we can see, by using an asterisk(*), we can directly call the functions from the imported module without prefixing it with module name.
D. dir() function:
The dir() function lists all the function names (or variable names) in a module.
Example:
Output: