A module in Python is a file containing Python definitions and statements. Modules help you organize your code into multiple files, and they allow you to reuse your code across different projects. Python has many built-in modules, and you can also use external modules that others have written.
How to use modules in Python?
To use a module, we need to import it into our program. You can import a module using the import
import math
After importing the math
module, you can use its functions. For example, let's find the square root of a number:
import math
result = math.sqrt(16)
print(result)
This will output 4.0
because the square root of 16 is 4.
Python's Built-In modules
Python comes with several built-in modules that provide useful functionality. Here are some examples:
math
module:
Provides mathematical functions like sqrt()
(square root), pi
(the mathematical constant), and more.
sqrt()
pi
import math
print(math.pi) # Output: 3.141592653589793
print(math.factorial(5)) # Output: 120
random
module:
Used for generating random numbers.
import random
print(random.randint(1, 100)) # Random integer between 1 and 100
datetime
module:
Helps you work with dates and times.
import datetime
now = datetime.datetime.now()
print(now) # Current date and time
How to install third-party libraries?
In addition to Python's built-in modules, there are many third-party libraries you can install. One way to install a library is by using the pip
Example: Installing the requests
library (used for making HTTP requests).
- Open your terminal or command prompt and run:
pip install requests
- Once installed, you can use it in your Python code:
import requests
response = requests.get("https://www.example.com")
print(response.status_code) # Output: 200 (if the website is available)
Summary
- Modules help you extend the functionality of Python by importing built-in or third-party code.
- You can use built-in modules like
,math
, andrandom
to perform common tasks.datetime
- To use third-party libraries, you can install them with
and then import them into your code.pip
Learning to use modules and libraries is one of the most important skills to improve your coding efficiency in Python. So, keep exploring and installing more libraries to make your programs even better!
Next steps
- Try exploring more Python modules such as
(for working with files and directories),os
(for system-specific parameters), orsys
(for working with JSON data).json
- Install a new library using
and use it in your code.pip