How to import modules and functions in Python?
- May 16, 2020 at 9:14 PM #3222Santhosh Kumar DKeymaster
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 change Firefox network connection timeout settings?
- The keyboard shortcut to minimize all windows in Windows 10
- How to disable Windows Sticky Keys?
- How to reset YouTube recommendations?
- Coding a simple Python BMI calculator using functions
- How to find Wi-Fi password when connected in Windows?
- How to save a web page on the Internet Archive?
- How to view frame by frame on YouTube?
- How to undo send in Gmail?
- How to set up undo send in Outlook?
- No program associated with filetype FileZilla
- How to import modules and functions in Python?
- How to restore previous session in Firefox?
- How to play the dinosaur game on Google Chrome?
- How to turn on dark mode in Firefox?