modules

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:

  1. math – Provides mathematical functions and operations
    • import math
    • result = math.sqrt(25)
    • print(result) # Output: 5.0
  2. 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
  3. datetime – Manipulates dates and times.
    • import datetime
    • current_time = datetime.datetime.now()
    • print(current_time) # Output: Current date and time
  4. os – Provides functions for interacting with the operating system.
    • import os
    • current_directory = os.getcwd()
    • print(current_directory) # Output: Current working directory
  5. 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
  6. requests – Simplifies making HTTP requests.
  7. 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
  8. time – Performs time-related operations and sleeps.
    • import time
    • current_time = time.time()
    • print(current_time) # Output: Current timestamp in seconds

Leave a comment