Practical – 155 : Perform basic operations using built-in modules and tools

1. Using the math Module

Performs mathematical operations.

import math

print(“Square root of 16:”, math.sqrt(16))

print(“Value of pi:”, math.pi)

print(“5 raised to power 3:”, math.pow(5, 3))

🔍 Analysis:

  • sqrt() returns the square root.
  • math.pi provides the constant π.
  • pow(x, y) gives x to the power y.

2. Using the datetime Module

Works with dates and times.

import datetime

today = datetime.date.today()

print(“Today’s date:”, today)

now = datetime.datetime.now()

print(“Current time:”, now.strftime(“%H:%M:%S”))

🔍 Analysis:

  • date.today() gets current date.
  • datetime.now() gets date + time.
  • strftime() formats output.

3. Using the random Module

Generates random numbers.

import random

print(“Random number between 1 and 10:”, random.randint(1, 10))

print(“Random choice from list:”, random.choice([‘red’, ‘green’, ‘blue’]))

🔍 Analysis:

  • randint(a, b) returns a random integer between a and b.
  • choice() selects a random item from a list.

4. Using the os Module

Interacts with the operating system.

import os

print(“Current working directory:”, os.getcwd())

print(“List of files:”, os.listdir())

🔍 Analysis:

  • getcwd() gets the current working directory.
  • listdir() lists files in that directory.

5. Using the sys Module

Accesses system-specific parameters.

import sys

print(“Python version:”, sys.version)

print(“Script name:”, sys.argv[0])

🔍 Analysis:

  • sys.version shows Python version.
  • sys.argv contains command-line arguments.

Summary of Tools and Use Cases

Module

Common Use

math

Math functions (sqrt, pi, pow)

datetime

Get and format date/time

random

Random numbers, shuffling, sampling

os

File system and environment info

sys

Python interpreter and script args