Python has a rich ecosystem of modules that provide additional functionality beyond what is available in the core language. These modules can be imported and used in your Python scripts to perform specific tasks. Here are some commonly used modules in Python along with examples:
math– Provides mathematical functions and operations- import math
- result = math.sqrt(25)
- print(result) # Output: 5.0
random– Generates random numbers and performs random selections.- import random
- random_num = random.randint(1, 10)
- print(random_num) # Output: Random number between 1 and 10
datetime– Manipulates dates and times.- import datetime
- current_time = datetime.datetime.now()
- print(current_time) # Output: Current date and time
os– Provides functions for interacting with the operating system.- import os
- current_directory = os.getcwd()
- print(current_directory) # Output: Current working directory
json– Allows encoding and decoding JSON data.- import json
- data = {‘name’: ‘John’, ‘age’: 25}
- json_data = json.dumps(data)
- print(json_data) # Output: JSON representation of the data
requests– Simplifies making HTTP requests.- import requests
- response = requests.get(‘https://www.example.com’)
- print(response.status_code) # Output: Status code of the response
csv– Provides functionality for reading and writing CSV files.- import csv
- with open(‘data.csv’, ‘r’) as file:
- reader = csv.reader(file)
- for row in reader:
- print(row) # Output: Each row of the CSV file
time– Performs time-related operations and sleeps.- import time
- current_time = time.time()
- print(current_time) # Output: Current timestamp in seconds