How to import modules and functions in Python?
- May 16, 2020 at 9:14 PM #3222Santhosh Kumar DKeymaster@santhosh
Modules are simply Python
.pyfiles containing Python code. Modules can be directly imported into other modules or into the main module. This eliminates the need to copy definitions and statements into each and every file that you code. Any Python file can be referenced as a module.
Importing a module.
For example, if you have a Python file named
tips.py, then its module name
tipscan be imported into other Python files or can be used on the Python command-line interpreter using the
importstatement is declared at the top of the code, under any general comments.
Python has many built-in modules that provide standard functionalities. Check the Python Standard Library for the full list of all built-in modules that come with every Python installation.
For example, to import the
mathmodule, you can use the following statement.
mathis a built-in module for providing mathematical functions, it will be directly imported from the Python Standard Library.
flaskis another Python module for mico web framework functions. It can be imported similarly.
flaskis not a built-in module of Python, you will get the following error.
ImportError: No module named 'flask'
So before importing it, you have to first install it using the Python command-line interpreter. To install a new module, you need to deactivate the Python interpreter using
And then install the module that you want using the
pipcommand. For example, the
flaskmodule can be installed using the following command.
pip install flask
Once installed, you can now import
flaskinto your Python code, and it will execute without the
Importing functions from within a module.
You can also import a specific function from within a Python module. You can do so by using the
fromkeyword followed by the name of the module and then the import statement for a specific function from within that module.
randomis a built-in module for generating random numbers. To import a specific function called
randintfrom within that module, you can use the following statement.
from random import randint
Modules – Python documentation
- How to voice type on Google Docs?
- What is Django framework?
- How to turn Google Assistant off?
- How to check the Python version?
- How to create a virtual environment in Python?
- How to change the directory in the Command Prompt?
- How to add a shortcode in WordPress PHP template file?
- Useful websites to research stocks
- How to check Linux uptime?
- How to check Linux last reboot time?
- How to ZIP and UNZIP files in Linux?
- How to change the file owner and group in Linux?
- Protect your email address with Firefox Relay
- How to change the language in Microsoft Office?
- How to get Twitter dark mode on desktop and mobile?