0% found this document useful (0 votes)
35 views134 pages

SWL All Practicals (Et22036)

The document outlines a practical assignment for creating and managing a database for a Daily Needs Shop using SQL. It includes objectives, theoretical concepts, SQL commands for database creation, data insertion, modification, and retrieval, as well as a flowchart of the process. Additionally, it discusses SQL constructs, operators, and differences between SQL and MySQL, along with further assignments related to vendor and customer databases.

Uploaded by

cajat99283
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views134 pages

SWL All Practicals (Et22036)

The document outlines a practical assignment for creating and managing a database for a Daily Needs Shop using SQL. It includes objectives, theoretical concepts, SQL commands for database creation, data insertion, modification, and retrieval, as well as a flowchart of the process. Additionally, it discusses SQL constructs, operators, and differences between SQL and MySQL, along with further assignments related to vendor and customer databases.

Uploaded by

cajat99283
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 134

Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OFTECHNOLOGY,


MANAGEMENT & RESEARCH , NAGPUR.
Practical No. 01
Aim: Create a Database “Items” of a Daily Needs Shop with following fields:
a) Item Number
b) Name of the Item
c) Price Per Item
d) Quantity Available
Add other fields as “Name of Vendor” & “Contact Number of Vendor”. Test the database by
taking at-least details of 10 items and display the same. Initially define item numbers as
“INT” and write down query to alter the data type of Item Number to “String”.

Name of Student: Ronak S. Wanjari


Roll No.: ET22036
Semester/Year: 6th/3rd
Academic Session:

Date of Performance:
Date of Submission:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)
OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To understand and choose appropriate constructs of SQL to create a database.
• To create appropriate SQL query and access a database as per given requirement.

THEORY:

SQL Theory Description for Managing a Daily Needs Shop


Structured Query Language (SQL) is a standardized language used to interact with relational
databases. This practical demonstrates the essential SQL operations required to create and
manage a database for a daily needs shop. The process includes creating the database structure,
adding data, modifying it as needed, and retrieving useful information. Here's a breakdown:

1. Database and Table Creation


The first step in managing a shop's inventory is defining its structure. Using the CREATE
DATABASE statement, we set up a database called DailyNeedsShop. Within this database, a
table named Items is created using the CREATE TABLE statement. This table includes columns
such as:
• ItemID: A unique identifier for each item.
• ItemName: The name of the item.
• Category: The type of item (e.g., Grocery, Dairy).
• Quantity: The stock available.
• Price: The cost per unit of the item.

2. Data Insertion
To populate the shop's inventory, we use the INSERT INTO statement. This allows us to add
records for items like Rice, Milk, and Shampoo, specifying their category, available quantity,
and price. This data ensures that the shopkeeper has a structured view of the inventory.

3. Data Type Modification


As the shop evolves, there may be a need to update the database structure. For instance, if
categories require longer descriptions, the ALTER TABLE statement can modify the data type of

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)
the Category column to accommodate larger text. This flexibility allows the database to adapt to
changing requirements.
4. Data Retrieval
To make informed decisions, the shopkeeper can use the SELECT statement to retrieve data:
• Display all items in the inventory.
• Filter specific categories (e.g., all items in the "Personal Care" category).
• View critical details like item names, quantities, and prices.

FLOWCHART:

Start

Create Database "Items"

Create Table with Required Fields

Input item details

Insert data into table

Display Table Contents

Alter ItemNumber Data Type

End

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)
PROGRAM:
mysql> CREATE DATABASE itemss;
mysql> use itemss;
Database changed
mysql> SHOW DATABASES;
mysql> CREATE TABLE itemdetails(
-> item_number INT NOT NULL PRIMARY KEY, -> name VARCHAR(100) NOT NULL,
->price_per_item DECIMAL(10, 2) NOT NULL, -> quantity_available INT NOT NULL
-> );
mysql> SHOW TABLES;
mysql> CREATE TABLE itemssd(
->item_number INT NOT NULL PRIMARY KEY, -> name VARCHAR(100) NOT NULL,
->price_per_item DECIMAL(10, 2) NOT NULL, -> quantity_available INT NOT NULL
-> );
mysql> DESCRIBE itemssd;
mysql> INSERT INTO itemssd (item_number, name, price_per_item, quantity_available) VALUES
(1, 'Toothpaste', 45.00, 100),
(2, 'Shampoo', 150.00, 50),
(3, 'Rice', 50.00, 200),
(4, 'Soap', 35.00, 150),
(5, 'Toilet Paper', 30.00, 80), (6, 'Milk', 60.00, 120),
(7, 'Sugar', 40.00, 100),
(8, 'Coffee Powder', 150.00, 60), (9, 'Washing Powder', 120.00, 80), (10, 'Detergent', 100.00, 150);
mysql> SELECT * FROM itemssd;
mysql> ALTER TABLE itemssd ADD Vendor Name VARCHAR(20), ADD Vendor Contact
BIGINT;
mysql> DESCRIBE itemssd;
mysql> UPDATE itemssd
-> SET VendorName = 'Vendor B', Vendor Contact = '9876543211' -> WHERE item_number = 2;
mysql> UPDATE itemssd
-> SET Vendor Name = 'Vendor C', Vendor Contact = '9876543212'
-> WHERE item_number = 3;
mysql> UPDATE itemssd
->SET VendorName = 'Vendor D', Vendor Contact = '9876543213' -> WHERE item_number = 4;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)
mysql> UPDATE itemssd
-> SET VendorName = 'Vendor E', Vendor Contact = '9876543214' -> WHERE item_number = 5;
mysql> UPDATE itemssd
-> SET VendorName = 'Vendor F', Vendor Contact = '9876543215' -> WHERE item_number = 6;
mysql> UPDATE itemssd
-> SET Vendor Name = 'Vendor G', Vendor Contact = '9876543216' WHERE item_number = 7;
mysql> UPDATE itemssd
-> SET VendorName = 'Vendor H', Vendor Contact = '9876543217' -> WHERE item_number = 8;
mysql> UPDATE itemssd
-> SET VendorName = 'Vendor I', Vendor Contact = '9876543218'
-> WHERE item_number = 9;
mysql> UPDATE itemssd
-> SET Vendor Name = 'Vendor J', Vendor Contact = '9876543219'
-> WHERE item_number = 10;
mysql> select * from itemssd;
mysql> ALTER TABLE itemssd
-> MODIFY COLUMN item_number VARCHAR(20);
mysql> DESCRIBE itemssd;

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

CONCLUSION:
The practical successfully demonstrated the creation and basic operations of a database system
for a Daily Needs Shop using SQL commands.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

DISCUSSION QUESTIONS:
1) List down the mostly used SQL constructs in creating a database.
And: When creating a database, the following SQL constructs are commonly used:
• CREATE:
o CREATE DATABASE: Creates a new database.
o CREATE TABLE: Creates a new table within a database.
o CREATE INDEX: Creates an index on a table to improve query performance.
o CREATE VIEW: Creates a virtual table based on the result of a query.
• ALTER:
o ALTER TABLE: Modifies the structure of an existing table.
• DROP:
o DROP TABLE: Deletes a table from the database.
o DROP DATABASE: Deletes an entire database.
o DROP INDEX: Deletes an index from a table.
• CONSTRAINTS (used within CREATE TABLE or ALTER TABLE):
o PRIMARY KEY: Defines a primary key constraint.
o FOREIGN KEY: Defines a foreign key constraint.
o UNIQUE: Ensures uniqueness for a set of columns.
o NOT NULL: Ensures a column cannot contain null values.
o CHECK: Imposes a condition that must be met for each row.
• DATA TYPES (used within CREATE TABLE or ALTER TABLE):
o Integer types (e.g., INT, BIGINT)
o Character types (e.g., VARCHAR, CHAR)
o Date and Time types (e.g., DATE, TIMESTAMP)
o Binary types (e.g., BLOB, BYTEA)

2) Elaborate about different types of SQL operators.


And: SQL operators are used to specify conditions in SQL commands and can be categorized into
several types:
• Arithmetic Operators:
o + (Addition)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)
o - (Subtraction)
o * (Multiplication)
o / (Division)
o % (Modulus)
• Comparison Operators:
o = (Equal to)
o <> or != (Not equal to)
o > (Greater than)
o (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
o LIKE (Pattern matching with wildcards)
o IN (Value is within a set)
o BETWEEN (Value is within a range)
• Logical Operators:
o AND (Combines two conditions, both must be true)
o OR (Combines two conditions, at least one must be true)
o NOT (Negates a condition)
• Bitwise Operators:
o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR)
o ~ (Bitwise NOT)
• Assignment Operators (used in stored procedures, functions, and triggers):
o := or = (Assigns a value to a variable)
• Set Operators (combine the results of two or more SELECT statements):
o UNION (Combines two result sets, removing duplicates)
o UNION ALL (Combines two result sets, including duplicates)
o INTERSECT (Returns rows common to both result sets)
o EXCEPT or MINUS (Returns rows in the first set but not the second)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 10
Software Workshop Lab (PCCET605P)
3) List down difference between SQL & MySQL.
Ans:
SQL MySQL

Defination SQL (Structured Query An open-source relational


Language): A standard database management system
programming language for (RDBMS).
managing relational databases.
Purpose Used for storing, Used for storing, manipulating,
manipulating, and retrieving and retrieving data, specifically
data in relational databases. designed to work with SQL.
Syntax Defines the standard syntax Implements SQL syntax with
for querying databases. some proprietary extensions
(e.g., LIMIT for pagination).
Development
Security Security depends on the Includes robust security features,
implementation and database such as access control and
system. encryption.

REFERENCE:

1. “SQL and Python Programming”, Bryan Johnson, 1st Edition, 2019, KDP Print US.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 11
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment No. 01
1. Aim: Construct a database of “List of Vendors” for a Honda Automotive Garage with the
following fields:
a) Name of Vendor
b) Name of Organization
c) Contact Number
Create a mechanism to update the database by adding the following fields:
i) Address of Vendor
ii) e-Mail ID
iii) Website, if any

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

Code:-
CREATE DATABASE honda_garage;
mysql> USE honda_garage;
mysql> CREATE TABLE vendors (
-> vendor_id INT AUTO_INCREMENT PRIMARY KEY,
-> vendor_name VARCHAR(100) NOT NULL,
-> organization_name VARCHAR(100) NOT NULL,
-> contact_number VARCHAR(15) NOT NULL
-> );

mysql> INSERT INTO vendors (vendor_name, organization_name, contact_number)


-> VALUES
-> ('Ronak', 'Honda Auto Parts', '111-222-3333'),
-> ('Ankit', 'Honda Repair Services', '444-555-6666'),
-> ('Amol', 'Honda Car Accessories', '777-888-9999');
mysql> SELECT * FROM vendors;

mysql> ALTER TABLE vendors


-> ADD COLUMN address VARCHAR(255),
-> ADD COLUMN email VARCHAR(100),
-> ADD COLUMN website VARCHAR(100);
mysql> DESCRIBE vendors;
mysql> UPDATE vendors
-> SET address = 'Mumbai, Maharashtra', email = '[email protected]', website =
'www.hondaautoparts.com'
-> WHERE vendor_name = 'Ronak';
mysql> UPDATE vendors
-> SET address = 'Delhi, NCR', email = '[email protected]', website =
'www.hondarepairservices.com'
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 2
Software Workshop Lab (PCCET605P)

-> WHERE vendor_name = 'Ankit';


mysql> UPDATE vendors
-> SET address = 'Bangalore, Karnataka', email = '[email protected]', website =
'www.hondacaraccessories.com'
-> WHERE vendor_name = 'Amol';
mysql> SELECT * FROM vendors;
output

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

AIM 2
Create a database of Customers for a branch of Axis Bank with the following fields:
a) Name of Account Holder
b) Account Number
c) Address
d) Contact Number
e) e-Mail ID
Create a mechanism to link the database by adding the following fields:
i) Aadhar Card Number
ii) PAN Card Number

code:
CREATE DATABASE axis_bank;
mysql> USE axis_bank;
Database changed
mysql> CREATE TABLE customers (
-> customer_id INT AUTO_INCREMENT PRIMARY KEY,
-> account_holder_name VARCHAR(100) NOT NULL,
-> account_number VARCHAR(20) NOT NULL UNIQUE,
-> address VARCHAR(255),
-> contact_number VARCHAR(15),
-> email VARCHAR(100)
-> );

mysql> INSERT INTO customers (account_holder_name, account_number, address,


contact_number, email)
-> VALUES
-> ('Ronak', 'AXIS100001', 'Mumbai', '9988776655', '[email protected]'),
-> ('Ankit', 'AXIS100002', 'Delhi', '8877665544', '[email protected]'),
-> ('Jayash', 'AXIS100003', 'Bangalore', '7766554433', '[email protected]');
mysql> SELECT * FROM customers;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

mysql> ALTER TABLE customers


-> ADD COLUMN aadhar_card_number VARCHAR(12),
-> ADD COLUMN pan_card_number VARCHAR(10);
Query OK, 0 rows affected (0.91 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> UPDATE customers
-> SET aadhar_card_number = '123456789012', pan_card_number = 'ABCDE1234F'
-> WHERE account_holder_name = 'Ronak';
mysql> UPDATE customers
-> SET aadhar_card_number = '223456789012', pan_card_number = 'XYZDE1234A'
-> WHERE account_holder_name = 'Ankit';
mysql> UPDATE customers
-> SET aadhar_card_number = '323456789012', pan_card_number = 'LMNOP1234Q'
-> WHERE account_holder_name = 'Jayash';
mysql> SELECT * FROM customers;

output

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 02
Aim: Consider the following Employee Tables:

EMPNO EMP_NAME DEPT_NAME SALARY DOJ BRANCH

11-JUNE-
E101 Vivek R &D 145000 Nagpur
2009

E102 Vishal Marketing 90000 15-MAR-2012 Pune

Product 20-JULY-
E103 Priyal 120000 Banglore
Development 2018
Product
E105 Shrushti 80000 19-SEPT-2019 Nagpur
Development
Product
E106 Pranay 100000 22-OCT-2018 Mumbai
Development

EMPNO EMP_NAME DESIGNATION DEPT_NAME


E101 Vivek Project Manager
E102 Vishal Sales Manager
E103 Priyal Design Architect
E105 Shrushti Software Developer
E106 Pranay Project Lead

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

Perform the following operations:


1. Display all the fields of the employee table.
2. Display number of employees
3. Retrieve employee numbers and their salary
4. Print total salary of all the employees
5. Retrieve the average salary of the employees
6. Display the names of the employees in descending order
Retrieve the name of employees and their dept name (using JOIN)

Name of Student: _Ronak S. Wanajri__


Roll No.: ET22036
Semester/Year: 6th/3rd
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)
OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To create appropriate SQL query and access a database as per given requirement.

THEORY:

In this practical, we are exploring several SQL operations commonly used in relational database
management systems (RDBMS) for querying and manipulating data. These operations focus on
retrieving, aggregating, and combining data from different tables.

1. Displaying All Fields of a Table: The SELECT * statement is used to display all fields
from a table. This operation retrieves every column and every row, giving a complete
view of the data stored in the table.

2. Counting Records: The COUNT() function is an aggregate function used to count the
number of rows in a table that meet certain conditions. It helps us determine how many
records exist, for example, counting the total number of employees in an employee table.

3. Retrieving Specific Columns: With SELECT column_name, we can retrieve specific


columns from a table, rather than displaying all data. This is useful when we need to
focus on particular attributes, such as employee numbers and salaries.

4. Calculating Total Values: The SUM() function is another aggregate function used to
calculate the total of a numeric column. In this case, it would be applied to sum the salary
column, providing the total salary paid to all employees.

5. Calculating the Average: The AVG() function calculates the average value of a numeric
column. It is commonly used to calculate metrics such as average salary, which gives
insights into the typical pay within the organization.

6. Sorting Data: The ORDER BY clause sorts data based on one or more columns. When
sorting in descending order, ORDER BY column_name DESC is used to arrange records
from highest to lowest, such as listing employees by salary or name.

7. Joining Tables: The JOIN operation is used to combine data from multiple tables based
on a common column. This allows us to retrieve related information from two or more
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 3
Software Workshop Lab (PCCET605P)
tables. For example, joining the employee table with the designation table to display
employee names along with their department and designation.

These SQL operations form the backbone of querying and analyzing relational data, allowing for
flexible and efficient data management. They help in retrieving specific information, performing
calculations, and combining data from multiple sources to provide valuable insights.

FLOWCHART:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

PROGRAM:

mysql> CREATE DATABASE EmployeeRB;


mysql> USE EmployeeRB;
mysql> CREATE TABLE Employee (
EMPNO VARCHAR(10) PRIMARY KEY,
EMP_NAME VARCHAR(50),
DEPT VARCHAR(50),
SALARY INT,
DOJ DATE,
BRANCH VARCHAR(50)
);
mysql> CREATE TABLE Employee_Designation ( EMPNO VARCHAR(10) PRIMARY KEY,
EMP_NAME VARCHAR(50), DESIGNATION VARCHAR(50));
mysql> INSERT INTO Employee (EMPNO, EMP_NAME, DEPT, SALARY, DOJ, BRANCH)
VALUES -> ('E101', 'Vivek', 'R&D', 145000, '2019-06-11', 'Nagpur '),
-> ('E102', 'Vishal', 'Marketing', 90000, '2012-03-15', 'Pune'),
-> ('E103', 'Priyal', 'Product Development', 120000, '2018-07-20', 'Bangalore'), -> ('E105',
'Shrushti', 'Product Development', 80000, '2019-09-19', 'Nagpur'),
-> ('E106', 'Pranay', 'Marketing', 100000, '2018-10-22', 'Mumbai');
mysql> INSERT INTO Employee_Designation (EMPNO, EMP_NAME, DESIGNATION)
VALUES -> ('E101', 'Vivek', 'Project Manager'),
-> ('E102', 'Vishal', 'Sales Manager'),
-> ('E103', 'Priyal', 'Design Architect'),
-> ('E105', 'Shrushti', 'Software Developer'),
-> ('E106', 'Pranay', 'Project Lead');
mysql> SELECT * FROM Employee;
mysql> SELECT * FROM Employee_Designation;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)
mysql> SELECT COUNT(*) AS Number_of_Employees FROM Employee;
mysql> SELECT EMPNO, SALARY FROM Employee;
mysql> SELECT SUM(SALARY) AS Total_Salary FROM Employee;
mysql> SELECT AVG(SALARY) AS Average_Salary FROM Employee;
mysql> SELECT EMP_NAME FROM Employee ORDER BY EMP_NAME DESC;
mysql> SELECT E. EMP_NAME, E.DEPT, ED.DESIGNATION
-> FROM Employee E
-> JOIN Employee_Designation ED ON E. EMPNO = ED. EMPNO;
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)
CONCLUSION:
This practical covered basic SQL operations such as data retrieval, aggregation (COUNT, SUM,
AVG), ordering, and joining tables to get meaningful insights from an employee database.

DISCUSSION QUESTIONS:
1) List down the operations that can be performed on a given database.
ANS-1] Data Definition Operations (DDL):
• CREATE: To create tables in the database (although this isn't explicitly mentioned, it's
implied for creating the necessary tables).
• ALTER: Modify the structure of the table if needed.
2] Data Manipulation Operations (DML):
• SELECT: Used to retrieve data from tables.
• INSERT: Adds data into tables (implied, though not explicitly mentioned).
• UPDATE: Modifies existing records (could be used to update fields).
• DELETE: Removes rows of data from the table (could be used, though not explicitly
mentioned).
3] Data Querying Operations:
• JOIN: Combines data from two or more tables, such as retrieving employee names with
their department and designation.
• ORDER BY: Sorts the data, e.g., sorting employee names in descending order.
• GROUP BY: Groups data (could be used for aggregate operations like counting
employees or summing salaries).

2) Discuss about the private and public keys.


ANS] In SQL, public and private keys are typically used in encryption and digital
signatures for securing data and ensuring confidentiality and integrity, particularly in
database management systems (DBMS) like MySQL or PostgreSQL. These are not directly
implemented as SQL operations, but can be integrated using certain extensions or functions.
Public Key:
• Used to encrypt data before storing it in the database.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)
• Can be shared publicly for users to encrypt data that only the owner (with the private key)
can decrypt.
Private Key:
• Used to decrypt data that was encrypted with the public key.
• It is kept secret by the database owner, ensuring only authorized decryption.

3) Elaborate the significance of JOIN and its types available in SQL.


ANS] Types of JOINs:

1. INNER JOIN: Retrieves rows with matching values in both tables. Non-matching rows
are excluded.
2. LEFT JOIN (LEFT OUTER JOIN): Retrieves all rows from the left table and
matching rows from the right table. Non-matching rows in the right table return NULL.
3. RIGHT JOIN (RIGHT OUTER JOIN): Retrieves all rows from the right table and
matching rows from the left table. Non-matching rows in the left table return NULL.
4. FULL JOIN (FULL OUTER JOIN): Retrieves all rows from both tables, with NULL
values where there is no match.
5. CROSS JOIN: Returns the Cartesian product of two tables, creating all possible row
combinations.
6. SELF JOIN: Joins a table with itself, often used for hierarchical data or comparisons
within the same table.
JOINs allow for efficient data retrieval from multiple tables, maintaining relational integrity
and reducing redundancy.

REFERENCE:

1. “SQL and Python Programming”, Bryan Johnson, 1st Edition, 2019, KDP Print US.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 10
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.2
Aim: 1. Construct a Food Inventory Table for Zomato as given below:

ITEM_ ITEM_NAME CATEGO PRICE STOCK EXPIRY_DAT


ID RY E
F101 Basmati Rice Grains 80 100 01-JAN-2026
F102 Brown Bread Bakery 40 50 15-JAN-2025
F103 Almond Butter Spreads 250 30 20-FEB-2025
F104 Whole Milk Dairy 60 200 10-DEC-2024
F105 Organic Honey Spreads 300 25 01-JUNE-2026

Also, create a Supplier Details Table for Zomato:


SUPPLIER_ID SUPPLIER_NAME CONTACT LOCATION
S301 Farmers' Co 9998765432 Nagpur
S302 Bake & Co 9876543219 Mumbai
S303 DairyFresh 9887654321 Pune
S304 NutriWorld 9923239957 Bangalore

1. Display all food items along with their stock and expiry date.
2. Find the total stock of items in the "Spreads" category.
3. Retrieve the details of food items that are expiring in the next 6 months.
4. Calculate the average price of items in the "Dairy" category.
5. Retrieve the names of suppliers who provide items with stock greater than 50.
6. Display all food items along with their supplier names (using JOIN).
7. Retrieve the names and prices of items priced above 200, along with their category and
supplier location.
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 1
Software Workshop Lab (PCCET605P)

2. Construct a Clothing Inventory Table for Amazon Outlet:

ITEM_ID ITEM_NAME CATEGORY PRICE STOCK SUPPLIE


R

C101 Denim Jeans Bottomwear 1500 30 Levis


C102 Cotton Shirt Topwear 1200 50 Raymond
C103 Silk Saree Ethnicwear 5000 20 Fabindia
C104 Woolen Sweater Winterwear 2000 15 Spark
C105 Sports T-Shirt Active Wear 800 60 Nike

Also construct a Supplier Details Table for Amazon Outlet:

SUPPLIER_ID SUPPLIER_NAME CONTACT


LOCATION
S201 Levi's 9876543210 Mumbai
S202 Raymond 9123456789 Delhi
S203 Fabindia 9988776655 Bangalore
S204 Monte Carlo 9345678123 Chandigarh
S205 Nike 9234567890 Pune

1. Display all the items available in the inventory.


2. Retrieve the names of items with stock less than 20.
3. Find the total value of stock for each category.
4. Display the average price of items in each category.
5. Retrieve the names of suppliers who supply items priced above 2000.
6. List all items along with their supplier names (using JOIN).
7. Retrieve details of items in the "Winterwear" category with stock greater than 10.

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

Code
CREATE DATABASE zomato_inventory;
mysql> USE zomato_inventory;
mysql> CREATE TABLE food_inventory (
-> item_id VARCHAR(10) PRIMARY KEY,
-> item_name VARCHAR(100),
-> category VARCHAR(50),
-> price DECIMAL(10, 2),
-> stock INT,
-> expiry_date DATE
-> );
mysql> INSERT INTO food_inventory (item_id, item_name, category, price, stock, expiry_date)
-> VALUES
-> ('F101', 'Basmati Rice', 'Grains', 80.00, 100, '2026-01-01'),
-> ('F102', 'Brown Bread', 'Bakery', 40.00, 50, '2025-01-15'),
-> ('F103', 'Almond Butter', 'Spreads', 250.00, 30, '2025-02-20'),
-> ('F104', 'Whole Milk', 'Dairy', 60.00, 200, '2024-12-10'),
-> ('F105', 'Organic Honey', 'Spreads', 300.00, 25, '2026-06-01');
mysql> SELECT * FROM food_inventory;

mysql> CREATE TABLE supplier_details (


-> supplier_id VARCHAR(10) PRIMARY KEY,
-> supplier_name VARCHAR(100),
-> contact VARCHAR(15),
-> location VARCHAR(100)
-> );
mysql> INSERT INTO supplier_details (supplier_id, supplier_name, contact, location)
-> VALUES
-> ('S301', 'Farmers'' Co', '9998765432', 'Nagpur'),
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 3
Software Workshop Lab (PCCET605P)

-> ('S302', 'Bake & Co', '9876543219', 'Mumbai'),


-> ('S303', 'DairyFresh', '9887654321', 'Pune'),
-> ('S304', 'NutriWorld', '9923239957', 'Bangalore');

mysql> SELECT * FROM supplier_details;

mysql> SELECT item_name, stock, expiry_date


-> FROM food_inventory;
mysql> SELECT SUM(stock) AS total_stock_in_spreads
-> FROM food_inventory
-> WHERE category = 'Spreads';

mysql> SELECT *
-> FROM food_inventory
-> WHERE expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(),
INTERVAL 6 MONTH);
mysql> SELECT AVG(price) AS average_price_dairy
-> FROM food_inventory
-> WHERE category = 'Dairy';
mysql> SELECT DISTINCT sd.supplier_name
-> FROM supplier_details sd
-> JOIN food_inventory fi
-> ON fi.item_id LIKE CONCAT('F', SUBSTRING(sd.supplier_id, 2));
Empty set (0.37 sec)

mysql> ALTER TABLE food_inventory


-> ADD COLUMN supplier_id VARCHAR(10);
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 4
Software Workshop Lab (PCCET605P)

mysql> UPDATE food_inventory


-> SET supplier_id = 'S301'
-> WHERE item_id = 'F101';
mysql> UPDATE food_inventory
-> SET supplier_id = 'S302'
-> WHERE item_id = 'F102';
mysql> UPDATE food_inventory
-> SET supplier_id = 'S303'
-> WHERE item_id = 'F103';
mysql> UPDATE food_inventory
-> SET supplier_id = 'S304'
-> WHERE item_id = 'F104';
mysql> UPDATE food_inventory
-> SET supplier_id = 'S304'
-> WHERE item_id = 'F105';
mysql> SELECT DISTINCT sd.supplier_name
-> FROM supplier_details sd
-> JOIN food_inventory fi ON fi.supplier_id = sd.supplier_id
-> WHERE fi.stock > 50;
mysql> SELECT fi.item_name, sd.supplier_name
-> FROM food_inventory fi
-> JOIN supplier_details sd
-> ON fi.item_id LIKE CONCAT('F', SUBSTRING(sd.supplier_id, 2));
mysql> SELECT fi.item_name, sd.supplier_name
-> FROM food_inventory fi
-> JOIN supplier_details sd ON fi.supplier_id = sd.supplier_id;
mysql> SELECT fi.item_name, fi.price, fi.category, sd.location
-> FROM food_inventory fi
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 5
Software Workshop Lab (PCCET605P)

-> JOIN supplier_details sd ON fi.supplier_id = sd.supplier_id


-> WHERE fi.price > 200;

Output

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

AIM2
Construct a Clothing Inventory Table for Amazon Outlet:

ITEM_ID ITEM_NAME CATEGORY PRICE STOCK SUPPLIE


R

C101 Denim Jeans Bottomwear 1500 30 Levis


C102 Cotton Shirt Topwear 1200 50 Raymond
C103 Silk Saree Ethnicwear 5000 20 Fabindia
C104 Woolen Sweater Winterwear 2000 15 Spark
C105 Sports T-Shirt Active Wear 800 60 Nike

Also construct a Supplier Details Table for Amazon Outlet:

SUPPLIER_ID SUPPLIER_NAME CONTACT


LOCATION
S201 Levi's 9876543210 Mumbai
S202 Raymond 9123456789 Delhi
S203 Fabindia 9988776655 Bangalore
S204 Monte Carlo 9345678123 Chandigarh
S205 Nike 9234567890 Pune

1. Display all the items available in the inventory.


2. Retrieve the names of items with stock less than 20.
3. Find the total value of stock for each category.
4. Display the average price of items in each category.
5. Retrieve the names of suppliers who supply items priced above 2000.
6. List all items along with their supplier names (using JOIN).
7. Retrieve details of items in the "Winterwear" category with stock greater than 10.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

CODE
mysql> CREATE DATABASE amazon_outlet;

Query OK, 1 row affected (0.07 sec)

mysql> USE amazon_outlet;

Database changed

mysql> CREATE TABLE clothing_inventory (

-> item_id VARCHAR(10) PRIMARY KEY,

-> item_name VARCHAR(100),

-> category VARCHAR(50),

-> price DECIMAL(10, 2),

-> stock INT,

-> supplier VARCHAR(100)

-> );

Query OK, 0 rows affected (0.35 sec)

mysql> INSERT INTO clothing_inventory (item_id, item_name, category, price, stock, supplier)

-> VALUES

-> ('C101', 'Denim Jeans', 'Bottomwear', 1500, 30, 'Levis'),

-> ('C102', 'Cotton Shirt', 'Topwear', 1200, 50, 'Raymond'),

-> ('C103', 'Silk Saree', 'Ethnicwear', 5000, 20, 'Fabindia'),

-> ('C104', 'Woolen Sweater', 'Winterwear', 2000, 15, 'Spark'),

-> ('C105', 'Sports T-Shirt', 'Active Wear', 800, 60, 'Nike');

mysql> SELECT * FROM clothing_inventory;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)

mysql> CREATE TABLE supplier_details (

-> supplier_id VARCHAR(10) PRIMARY KEY,

-> supplier_name VARCHAR(100),

-> contact VARCHAR(15),

-> location VARCHAR(100)

-> );

Query OK, 0 rows affected (0.32 sec)

mysql> INSERT INTO supplier_details (supplier_id, supplier_name, contact, location)

-> VALUES

-> ('S201', 'Levi\'s', '9876543210', 'Mumbai'),

-> ('S202', 'Raymond', '9123456789', 'Delhi'),

-> ('S203', 'Fabindia', '9988776655', 'Bangalore'),

-> ('S204', 'Monte Carlo', '9345678123', 'Chandigarh'),

-> ('S205', 'Nike', '9234567890', 'Pune');

mysql> SELECT * FROM supplier_details;

mysql> SELECT * FROM clothing_inventory;

mysql> SELECT item_name

-> FROM clothing_inventory

-> WHERE stock < 20;

mysql> SELECT category, SUM(price * stock) AS total_stock_value

-> FROM clothing_inventory

-> GROUP BY category;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 10
Software Workshop Lab (PCCET605P)

mysql> SELECT category, AVG(price) AS average_price

-> FROM clothing_inventory

-> GROUP BY category;

mysql> SELECT DISTINCT sd.supplier_name

-> FROM supplier_details sd

-> JOIN clothing_inventory ci ON ci.supplier = sd.supplier_name

-> WHERE ci.price > 2000;

mysql> SELECT ci.item_name, ci.price, ci.category, sd.supplier_name

-> FROM clothing_inventory ci

-> JOIN supplier_details sd ON ci.supplier = sd.supplier_name;

mysql> SELECT *

-> FROM clothing_inventory

-> WHERE category = 'Winterwear' AND stock > 10;

OUTPUT

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 11
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 12
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 03
Aim: Develop a Database “Students” of an Institute. Create a table with following attributes:
a) Roll Number
b) Name of the student
c) Department
d) Year
e) Section
f) Contact Number
g) Email ID
Add another other attributes as “CGPA” in the above mentioned table. Insert details of at-
least 10 students taken from the end user in the table and display the detailed table. Generate
the sorted reports based on the following criteria:
a) List of students with roll numbers in increasing order
b) List of the students with decreasing order of CGPA.
c) List the students with the Minimum and maximum CGPA.

Name of Student: Ronak S.Wanjari


Roll No.: ET22036
Semester/Year: VI/III
Academic Session:
Date of Performance:__________
Date of Submission: __________
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 1
Software Workshop Lab (PCCET605P)
OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To understand and choose appropriate constructs of SQL to create a database.
• To create appropriate SQL query to generate various reports as per given requirements.

THEORY:

In this practical, we will be working with a database management system (DBMS) to create and
manipulate a database called "Students” using MYSQL. The database will store information
about students in an institute, including their roll number, name, department, year, section,
contact number, e-mail ID, and CGPA in tabular form. Each row in the table represents a tuple
consisting of data related to each student, and each column represents a specific attribute of that
student.

The first step is to design the table structure by specifying the attributes and their data types.

Based on the given requirements, the table structure will include the following attributes:

• Roll Number: This attribute will store a unique identification number assigned to
each student. Name of the student: This attribute will store the name of the student.

• Department: This attribute will store the department in which the student is
enrolled.

• Year: This attribute will store the year in which the student is studying.

• Section: This attribute will store the section in which the student is assigned.

• Contact Number: This attribute will store the contact number of the student.

• Email ID: This attribute will store the email address of the student.
• CGPA: This attribute will store the Cumulative Grade Point Average of the
student.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)
FLOWCHART:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)
PROGRAM:

import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="student_in"
)
cursor = conn.cursor()
for i in range(10):
print(f"Enter details for Student {i + 1}:")
roll = int(input("Roll Number: "))
name = input("Name: ")
department = input("Department: ")
year = int(input("Year: "))
section = input("Section: ")
contact = input("Contact Number: ")
email = input("Email ID: ")
cgpa = float(input("CGPA: "))
cursor.execute(
"INSERT INTO StudentDetails (RollNo, Name, Department, Year, Section, ContactNo,
EmailID, CGPA) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
(roll, name, department, year, section, contact, email, cgpa)
)
conn.commit()
print("Data inserted successfully!")

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)
conn.close()

SQL code:
mysql> CREATE DATABASE student_in;
mysql» USE student_in;
mysql> CREATE TABLE IF NOT EXISTS Student Details ( RollNO INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(50),
Year INT,
Section VARCHAR(5),
ContactNo VARCHAR(15),
EmailID VARCHAR(100),
CGPA FLOAT
-> );
mysql> show tables;
mysql> describe StudentDetails;
mysql> select * from StudentDetails;
mysql> SELECT *FROM StudentDetails ORDER BY RollNo ASC;
mysql> SELECT *FROM StudentDetails ORDER BY CGPA DESC;
mysql> SELECT * FROM StudentDetails WHERE CGPA=(select MAX(CGPA) from Student
Details);
mysql> SELECT * FROM StudentDetails WHERE CGPA=(select MIN(CGPA) from
StudentDetails);

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)
CONCLUSION: We successfully implemented a program to collect, process, and store student
information in a MySQL database using Python. The program established a seamless connection
between Python and MySQL, enabling the insertion of multiple student records into the database
through user inputs.

DISCUSSION QUESTIONS:
1) Elaborate about the subsets of SQL.
Ans: Subsets of SQL:SQL has three primary subsets:

• DDL (Data Definition Language): Defines the structure of the database (e.g., CREATE, ALTER,
DROP).
• DML (Data Manipulation Language): Manipulates data in tables (e.g., INSERT, UPDATE,
DELETE, SELECT).
• DCL (Data Control Language): Manages user access and permissions (e.g., GRANT, REVOKE).
• TCL (Transaction Control Language): Manages transactions in a database (e.g., COMMIT,
ROLLBACK).

2) Discuss about normalization in a database.


Ans: Normalization is the process of organizing data in a database to reduce redundancy and
improve data integrity. It involves dividing a database into smaller tables and defining
relationships between them. Normalization is achieved in forms like:
• 1NF (First Normal Form): Eliminate duplicate columns.
• 2NF (Second Normal Form): Ensure all non-key attributes depend on the primary key.
• 3NF (Third Normal Form): Remove transitive dependencies.
Normalization optimizes storage and maintains consistency.

3) Illustrate about ACID property in a database.


Ans: The ACID properties ensure reliable transactions in databases:
Atomicity: A transaction is either fully completed or not at all.
Consistency: Ensures the database remains in a valid state after a transaction.
Isolation: Concurrent transactions do not affect each other.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)
Durability: Changes from committed transactions are permanent.
These properties maintain data integrity and ensure reliability in multi-user environments.

REFERENCE:

1. “SQL and Python Programming”, Bryan Johnson, 1st Edition, 2019, KDP Print US.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 10
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.3
Aim: 1. Develop a database "Employees" of Persistent Systems Limited, Nagpur.
Create a table with the following attributes:
a) Employee ID
b) Name of the employee
c) Department
d) Designation
e) Salary
f) Contact Number
g) e-Mail ID
h) Date of Joining
Add another attribute "Performance Rating" in the table. Insert details of at least 10 employees
taken from the end user in the table and display the detailed database.
Generate sorted reports based on the following criteria:
a) List of employees with Employee ID in an ascending order.
b) List of employees with descending order of Performance Rating.
c) List of employees with the minimum and maximum salary.
d) Display the name of employee whose name contain letter “y”

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 1
Software Workshop Lab (PCCET605P)

Date of Performance:__________
Date of Submission: __________

Code:-
mysql> CREATE DATABASE PersistentEmployees;
mysql> USE PersistentEmployees;
Database changed
mysql> CREATE TABLE EmployeeDetails (
-> EmployeeID INT AUTO_INCREMENT PRIMARY KEY,
-> Name VARCHAR(100) NOT NULL,
-> Department VARCHAR(50) NOT NULL,
-> Designation VARCHAR(50) NOT NULL,
-> Salary DECIMAL(10, 2) NOT NULL,
-> ContactNumber VARCHAR(15),
-> EmailID VARCHAR(100) UNIQUE NOT NULL,
-> DateOfJoining DATE NOT NULL
-> );
mysql> ALTER TABLE EmployeeDetails
-> ADD COLUMN PerformanceRating VARCHAR(10);
mysql> describe EmployeeDetails;
->SELECT * FROM EmployeeDetails
ORDER BY EmployeeID ASC;
->SELECT * FROM EmployeeDetails
ORDER BY PerformanceRating DESC;
->SELECT * FROM EmployeeDetails
ORDER BY Salary ASC
LIMIT 1 ;

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

->SELECT * FROM EmployeeDetails


ORDER BY Salary DESC
LIMIT 1 ;

->SELECT * FROM EmployeeDetails


WHERE Name LIKE '%y%';
Python code:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="Employees"
)
cursor = conn.cursor()
for i in range(10):
print(f"Enter details for Employee {i + 1}:")
emp_id = int(input("Employee ID: "))
name = input("Name: ")
department = input("Department: ")
designation = input("Designation: ")
salary = float(input("Salary: "))
contact_number = input("Contact Number: ")
email = input("Email: ")
date_of_joining = input("Date of Joining (YYYY-MM-DD): ")
performance_rating = int(input("Performance Rating: "))
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 3
Software Workshop Lab (PCCET605P)

cursor.execute(
"INSERT INTO Employee (EmployeeID, Name, Department, Designation, Salary,
ContactNumber, Email, DateOfJoining, PerformanceRating) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
(emp_id, name, department, designation, salary, contact_number, email, date_of_joining,
performance_rating)
)
conn.commit()
print("Data inserted successfully!")
conn.close()

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

AIM 2: Create a database "Books" for Atal Bihari Vajpeyee Public Library.
Construct a table with the following fields:
a) Title of the book
b) Name of Author
c) Publication House
d) Year of Publication
e) ISBN Number
f) Language
g) Price
h) Available Copies
Insert details of at least 10 books taken from the end user in the table and display the detailed
database.
Generate sorted reports based on the following criteria:
a) List of books by ISBN Numbers in ascending order.
b) List of books by Year of Publication in a descending order.
c) Display the names of books whose price is in between Rs.500 to
Rs.1000.
Create a mechanism to search the availability of the book in the library based on:
a) Keyword in the Title of Book
b) Name of Author
c) ISBN Number

SQL CODE:
mysql> CREATE DATABASE Books;

mysql> USE Books;


Database changed
mysql> CREATE TABLE BookDetails (
-> Title VARCHAR(255) NOT NULL,
-> AuthorName VARCHAR(255) NOT NULL,
-> PublicationHouse VARCHAR(255),
-> YearOfPublication YEAR,
-> ISBNNumber VARCHAR(20) UNIQUE NOT NULL,
-> Language VARCHAR(50),
-> Price DECIMAL(10, 2),
-> AvailableCopies INT,
-> PRIMARY KEY (ISBNNumber)
-> );
mysql> select * from BookDetails;
SELECT Title, ISBNNumber
FROM BookDetails
ORDER BY ISBNNumber ASC;
SELECT Title, YearOfPublication
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 6
Software Workshop Lab (PCCET605P)

FROM BookDetails
ORDER BY YearOfPublication DESC;
SELECT Title, Price
FROM BookDetails
WHERE Price BETWEEN 500 AND 1000;
SELECT * FROM BookDetails
WHERE Title LIKE '%ABC%';
SELECT * FROM BookDetails
WHERE AuthorName LIKE '%Z%';
SELECT * FROM BookDetails
WHERE ISBNNumber = '12345';

Python Code:
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="Books"
)

cursor = conn.cursor()
# Insert details of 4 books with short names
books = [
("ABC", "X", "Pub1", 2020, "12345", "English", 250.00, 5),
("DEF", "Y", "Pub2", 2019, "67890", "English", 300.00, 3),
("GHI", "Z", "Pub3", 2021, "11223", "English", 150.00, 7),
("JKL", "A", "Pub4", 2018, "44556", "English", 200.00, 4)
]

for book in books:


cursor.execute(
"INSERT INTO BookDetails (Title, AuthorName, PublicationHouse, YearOfPublication,
ISBNNumber, Language, Price, AvailableCopies) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
book
)
conn.commit()
print(f"Data for '{book[0]}' inserted successfully!")

conn.close()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 04
Aim: Examine the provided image “moonlanding.png”, which is heavily contaminated with
periodic noise. Clean up the noise using the Fast Fourier Transform (FFT). Find and use the 2-D
FFT function in “scipy.fftpack”, and plot the FFT spectrum of the image. The spectrum consists
of high and low frequency components. The noise is contained in the high-frequency part of the
spectrum, so set some of those components to zero (Hint: use array slicing). Apply the inverse
Fourier transform to reconstruct the resulting image.

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with the different methods available in SciPy Library.
• To learn and apply the Fast Fourier Transform Package (FFTPack) of SciPy Library for
image processing.

THEORY:

The Fast Fourier Transform (FFT) is an efficient algorithm for computing the Discrete Fourier
Transform (DFT) of a sequence or array of data. The DFT is a mathematical transformation that
converts a signal from the time or spatial domain into the frequency domain, revealing the
amplitudes and phases of different frequency components present in the signal.

In the SciPy library, the Fast Fourier Transform (FFT) functionality is provided by the scipy.fft
module. This module offers several functions for performing FFT computations, including both
one-dimensional (1-D) and two-dimensional (2-D) FFTs. The theory behind the FFT used in
SciPy is based on the principles of the Cooley-Tukey algorithm and the Fast Fourier Transform.

The scipy.fft module provides various functions for performing FFT computations. The main
functions include:

● fft(): Computes the 1-D FFT of a signal.

● ifft(): Computes the 1-D inverse FFT, which transforms the signal from the frequency
domain back to the time domain.
● fft2(): Computes the 2-D FFT of an array, such as an image.

● ifft2(): Computes the 2-D inverse FFT.

Efficiency and Performance: The SciPy FFT implementation in the scipy.fft module is highly
optimized for performance. It leverages efficient algorithms and techniques, such as

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

vectorization and utilizing lower-level libraries like FFTPACK or Intel MKL, to accelerate the
computations.

The FFT functions in SciPy provide additional options to control the behavior of the FFT
computation. These options include specifying the input data type, choosing the size and shape
of the output, selecting different FFT algorithms (e.g., FFTPACK, FFTW), applying
normalization, and more.

By using the functions available in the scipy.fft module, you can efficiently compute the FFT
and inverse FFT of one-dimensional or two-dimensional data in the SciPy library. These
functions provide a convenient way to analyze signals and images in the frequency domain,
enabling tasks such as spectral analysis, filtering, deconvolution, and more.

FLOWCHART:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

PROGRAM:

import matplotlib.pyplot as plt


import numpy as np
from scipy import fftpack
from scipy import ndimage

image = plt.imread('moonlanding.png').astype(float) #READING THE IMAGE


plt.figure()
plt.imshow(image,plt.cm.gray)
plt.title('original image')
plt.show()

image_fft = fftpack.fft2(image)
def plot_spectrum(image_fft):
from matplotlib.colors import LogNorm
plt.imshow(np.abs(image_fft), norm=LogNorm(vmin=5))
plt.colorbar()

plt.figure()
plot_spectrum(image_fft)
plt.title('Fourier transform')
plt.show()

#APPLYING FILTERING
keep_fraction = 0.1
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 4
Software Workshop Lab (PCCET605P)

im_fft2 = image_fft.copy()
r, c = im_fft2.shape
im_fft2[int(r*keep_fraction):int(r*(1-keep_fraction))] = 0
im_fft2[:, int(c*keep_fraction):int(c*(1-keep_fraction))] = 0
plt.figure()
plot_spectrum(im_fft2)
plt.title('Filtered Spectrum')
plt.show()

im2=fftpack.ifft2(im_fft2).real
plt.figure()
plt.imshow(im2,plt.cm.gray)
plt.title('reconsructed Signal')
plt.show()

#Bluring image
im_blur = ndimage.gaussian_filter(image, 4)
plt.figure()
plt.imshow(im_blur, plt.cm.gray)
plt.title('Blurred image')
plt.show()
#edge strength
sobel_x = ndimage.sobel(image, axis=0)
sobel_y = ndimage.sobel(image, axis=1)
# Calculate edge strength as the magnitude of the gradient

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

edge_strength = np.hypot(sobel_x, sobel_y)


# Display the edge strength image
plt.figure()
plt.imshow(edge_strength, cmap='gray')
plt.title('Edge Strength')
plt.colorbar()
plt.show()

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

CONCLUSION:
By applying the Fast Fourier Transform (FFT) to the image, we were able to examine its
frequency spectrum. The high-frequency components of the spectrum correspond to the noise
in the image. By setting some of those high-frequency components to zero, we effectively
filtered out the noise. Applying the inverse Fourier transform to the modified spectrum
resulted in a cleaned version of the image, where the periodic noise was significantly reduced.

DISCUSSION QUESTIONS:
1) Illustrate the significance of SciPy Library in data processing.
Ans}Significance of SciPy in Data Processing:
• Numerical Operations: Fast computations for integration, interpolation, and linear
algebra.
• Signal & Image Processing: FFT, filtering, and edge detection.
• Statistical Analysis: Probability distributions, hypothesis testing, and curve fitting.
• Sparse Matrix Handling: Efficient operations on large datasets.
• Optimization: Tools for function minimization and equation solving.
• Interoperability: Seamless integration with NumPy, Matplotlib, and Pandas.

2) List down the different methods/packages available in SciPy Library.


Ans}Different Methods/Packages in SciPy Library:
1. scipy.fftpack: Fast Fourier Transform (FFT) for signal and image processing.
2. scipy.linalg: Linear algebra operations (eigenvalues, matrix decompositions).
3. scipy.optimize: Optimization techniques (minimization, curve fitting, root finding).
4. scipy.stats: Statistical functions (distributions, hypothesis testing).
5. scipy.sparse: Sparse matrix operations for large datasets.
6. scipy.signal: Signal processing (filtering, convolution, waveforms).
7. scipy.ndimage: Image processing (filters, morphology, measurements).
8. scipy.cluster: Clustering algorithms (hierarchical clustering, k-means).

3) List down various tools available for image processing.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)

Ans}Various Tools for Image Processing:


1. SciPy (scipy.ndimage): Filters, morphological operations, and measurements.
2. OpenCV: Real-time image processing (face detection, object tracking, filtering).
3. Pillow (PIL): Image opening, manipulation, and saving (resize, crop, filters).
4. Matplotlib: Image visualization and plotting.
5. NumPy: Image array manipulation and mathematical operations

REFERENCE:

1. “SciPy and NumPy”, Eli Bressert, 2nd Edition, 2013, O’Reilly Media Inc.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 10
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.4
AIM: 1. Read the famous painting of Leonardo Da Vinci of “Mona Lisa” in JPEG
format and perform the following operations:
a) Create a mechanism to remove the noise.
b) Sharpen the image using numpy & scipy libraries
c) Apply the Edge Detection Technique
d) Display the Original & Edge Detected output images
Name of Student: _Ronak Wanjari__
Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
# Load image
image = Image.open("mona.jpeg").convert("RGB")
# Remove noise (Gaussian Blur)
denoised = image.filter(ImageFilter.GaussianBlur(1)) # Light blur to keep details
# Sharpen image (Unsharp Mask for better effect)
sharpened = denoised.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=3))
# Edge detection
edges = image.convert("L").filter(ImageFilter.FIND_EDGES)
# Show all images in one figure
titles = ["Original", "Denoised", "Sharpened", "Edges"]
images = [image, denoised, sharpened, edges]
plt.figure(figsize=(10, 8))
for i, (img, title) in enumerate(zip(images, titles), 1):
plt.subplot(2, 2, i)
plt.imshow(img, cmap="gray" if title == "Edges" else None)
plt.title(title)
plt.axis("off")
plt.tight_layout()
plt.show()
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

AIM: 2]Read your own colored image in PNG format and create a mechanism to
convert your colored image into famous Microsoft “Sepia Image”

CODE:
from PIL import Image
# Open the original image
image = Image.open("ronak.jpeg")
image = image.convert("RGB")
# Apply sepia filter
pixels = image.load()
for x in range(image.width):
for y in range(image.height):
R, G, B = pixels[x, y]
oR = min(255, int(R * 0.393 + G * 0.769 + B * 0.189))
oG = min(255, int(R * 0.349 + G * 0.686 + B * 0.168))
oB = min(255, int(R * 0.272 + G * 0.534 + B * 0.131))
pixels[x, y] = (oR, oG, oB)
# Save and show the image
image.save("sepia.jpeg")
image.show()

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 05
Aim: Import an image “face.jpg” from package of “scipy.ndimage” and perform the
following operations on it:
a) Display the image using pyplot
b) Display the image up-side down
c) Rotate the image with an angle of 450
d) Apply the filters and blur the image
e) Apply the edge detection technique to it

Name of Student: ___RONAK S WANJARI_


Roll No.: ___ET22036___________
Semester/Year: ______________
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with image processing techniques available in ndimage package of
SciPy Library.
• To apply various image processing techniques available in ndimage package of
SciPy Library.

THEORY:

SciPy is a scientific computing library for Python that provides functionality for numerical
integration, optimization, linear algebra, signal and image processing, statistical analysis, and
more. It builds upon NumPy, another Python library, and extends its capabilities by offering
additional tools and algorithms for scientific and technical computing tasks. SciPy is widely
used in fields such as physics, engineering, mathematics, and data science.

In this practical, we have to perform the following operations on image:

a) Display the image using pyplot


To show pyplot images on a console, we can use pyplot.show() method.

• Set the figure size and adjust the padding between and around the subplots.
• Use imshow() method, with data.
• Display the data as an image, i.e., on a 2D regular raster.
• To display the figure, use show()method

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

b) Display the image up-side down


The ImageOps module of the Python image processing library Pillow(PIL) which provides
flip() function to flip the image upside down (vertically) and mirror() to flip the left and right
(horizontally).

c) Rotate the image with an angle of 450 From PIL -- Python Image Library is a
module that

• contains in-built functions to manipulate and

• work with image as an input to the functions. image.rotate(angle)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

d) Apply the filters and blur the image

It applies a blurring effect on to the image as specified through a specific kernel or a


convolution matrix.
filter(ImageFilter.BLUR)

Original Blurred

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

FLOWCHART:

PROGRAM:

import matplotlib.pyplot as plt


import numpy as np
from scipy import datasets
from scipy import misc, ndimage
image = datasets.face()
plt.imsave('face.jpg', image)
plt.imshow(image)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

plt.show()
up_side_down = np.flipud(image)
plt.imshow(up_side_down)
plt.title("inverse image")
plt.show()

rotate_image = ndimage.rotate(image, -45)


plt.imshow(rotate_image)
plt.show()
blurred_image = ndimage.gaussian_filter(image, sigma=5)
plt.imshow(blurred_image)
plt.title('Blurred Image')
plt.axis('off')
plt.show()
gray_image = np.mean(image, axis=2)
sobel_x = ndimage.sobel(gray_image, axis=0, mode='constant')
sobel_y = ndimage.sobel(gray_image, axis=1, mode='constant')
edge_Strenght = np.hypot(sobel_x, sobel_y)
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image)
axes[0].set_title('original image')
axes[1].imshow(edge_Strenght, cmap='gray')
axes[1].set_title('edge detection')
plt.show()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

CONCLUSION:
Here we have successfully performed various operations on image using the scipy library.

DISCUSSION QUESTIONS:
1) Determine the significance of ndimage package available in SciPy Library.
ANS}Significance of scipy.ndimage in SciPy:
• Filtering: Gaussian, median, and uniform filters for smoothing images.
• Morphological Operations: Erosion, dilation, opening, and closing.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

• Measurements: Find object properties like area, center, and perimeter.


• Interpolation: Resize and rotate images.
• Edge Detection: Sobel and Prewitt filters for detecting edges.

2) List out the important features of ndimage package.


ANS}Important Features of scipy.ndimage:
1. Filtering: Gaussian, median, and uniform filters for noise reduction.
2. Interpolation: Image rotation, zooming, and shifting.
3. Morphology: Erosion, dilation, opening, and closing operations.
4. Edge Detection: Sobel, Prewitt, and Laplace filters for detecting edges.
5. Measurements: Calculate object properties like area, centroid, and bounding boxes.
6. Labeling: Identify and label connected components in images.
7. Fourier Transform: Frequency domain filtering for denoising.

REFERENCE:

1. “SciPy and NumPy”, Eli Bressert, 2nd Edition, 2013, O’Reilly Media Inc.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.5
AIM:
1. Read a gray scale picture of “Mount Everest” in JPG format and perform
the following operations:
a) Convert the gray scale picture into a colored image
b) Create a mechanism to display the mirror image of colored Mount
Everest.
c) Create a mechanism to focus on the peak of Mount Everest (displaying
only the peak of Mount Everest)
Name of Student: _Ronak Wanjari__
Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import cv2
import matplotlib.pyplot as plt
# Load grayscale image
image = cv2.imread("mount.jpeg", cv2.IMREAD_GRAYSCALE)
# Convert to colored image
colored_image = cv2.applyColorMap(image, cv2.COLORMAP_JET)
# Create mirror image
mirror_image = cv2.flip(colored_image, 1)
# Crop to focus on peak
x, y, w, h = 200, 50, 300, 200
peak_image = colored_image[y:y+h, x:x+w]
# Display all images
titles = ["Grayscale", "Colored", "Mirror Image", "Focused Peak"]
images = [image, colored_image, mirror_image, peak_image]
plt.figure(figsize=(12, 6))
for i in range(4):
plt.subplot(1, 4, i+1)
plt.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB) if i > 0 else images[i],
cmap='gray' if i == 0 else None)
plt.title(titles[i])
plt.axis('off')

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

AIM :2. Create a program to display a 3D-Spiral Graph. Develop a mechanism to


rotate the Spiral Graph in 3600 degrees. Apply the similar technique to any
3D-Object and create a mechanism to inspect the 3D- Object in 3600
degrees.

CODE:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Create a figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate Spiral Data

t = np.linspace(0, 4*np.pi, 100)


x = np.sin(t)
y = np.cos(t)
z=t

# Plot the Spiral


ax.plot3D(x, y, z, 'b', linewidth=2)

# Function to Rotate the 3D Plot


def update(angle):
ax.view_init(elev=20, azim=angle)

# Animate Rotation
ani = animation.FuncAnimation(fig, update, frames=360, interval=20)
plt.show()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 06
Aim: Perform statistical analysis using the scipy.stats module in Python. Explore various
statistical functions provided by SciPy to analyze a given dataset.
Read the dataset “brain_size.csv” containing different values of three different IQ measures,
details of subject weight, height and brain size (as per MRI) and perform the following
operations:
a) Display the first few rows of the dataset
b) Display the different data types in the dataset
c) Display the descriptive statics such as mean, variance, skewness and kurtosis.
d) Generate the statistical report based on the gender of the subject
e) Visualize the dataset by displaying the weights & heights of each subject
f) Display the histogram of weights & heights

Name of Student: _RONAK S. WANJARI_


Roll No.: __ET22036____________
Semester/Year: ______________
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with statistical modules available in stats package of SciPy Library.
• To apply various statistical modules available in stats package of SciPy Library.

THEORY:

Statistical Analysis using SciPy in Python

Introduction to Statistical Analysis


Statistical analysis is the process of collecting, organizing, analyzing, interpreting, and
presenting data. It helps in understanding patterns, relationships, and trends in data. Python
provides powerful libraries for statistical analysis, such as NumPy, pandas, Matplotlib, and
SciPy. The scipy.stats module is specifically designed to perform a wide range of statistical
operations.
Understanding scipy.stats
The scipy.stats module provides various statistical functions, including:
• Descriptive statistics (mean, median, mode, variance, standard deviation, etc.)
• Probability distributions (normal, binomial, Poisson, etc.)
• Statistical tests (t-test, chi-square test, ANOVA, etc.)
• Correlation and regression analysis
Understanding Key Statistical Concepts
Descriptive Statistics
Descriptive statistics summarize and describe the main features of a dataset.
• Mean (Average): The sum of all values divided by the number of values.
• Variance: Measures the spread of data points from the mean.
• Skewness: Indicates whether data is symmetric or skewed.
o Positive skew: Tail is on the right.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

o Negative skew: Tail is on the left.


• Kurtosis: Measures the "tailedness" of a distribution.
o High kurtosis: Heavy tails (outliers present).
o Low kurtosis: Light tails.
FLOWCHART:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

PROGRAM:

import pandas as pd
import scipy
data=pd.read_csv('brain_size.csv',sep=";",na_values=".")
print("Displaying the contents of files:")
print(data)
print("displaying the first few rows of datasets")
print(data.head())
print("displaying the data types of columns:")
print(data.dtypes)
print("displaying the description statistics of given dataset")
print(data.describe())
gender=data.groupby('Gender')
print("displaying the description statistics -Genderwise:")
print(gender.describe())
print("displaying the -Genderwise mean values:")
print(gender.mean())
print("displaying the description statistics -Genderwise:")
print(gender.size())
from scipy.stats import skew
print(" displaying the skewness")
print("Skewness for FSIQ:",skew(data['FSIQ']))
from scipy.stats import kurtosis
print("displaying the kurtosis")
print("kurtosis for FSIQ:",kurtosis(data['FSIQ']))
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 4
Software Workshop Lab (PCCET605P)

print("displaying relationship between different parameters")


from pandas import plotting
import matplotlib.pyplot as plt
data['Height'].fillna(method='pad', inplace=True)
plotting.scatter_matrix(data[['VIQ','MRI_Count','Height']],
c=(data['Gender']=='Female'),marker='o',
alpha=1,cmap='winter')
fig=plt.gcf()
fig.suptitle("blue:male,green:female",size=13)
plt.show()
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

CONCLUSION:
Here we have successfully hands-on with various statistical modules available in stats package of
SciPy Library..

DISCUSSION QUESTIONS:
1) Determine the significance of stats package available in SciPy Library.
Ans} Significance of scipy.stats Package
The scipy.stats module is a crucial part of the SciPy library that provides various
statistical functions for data analysis, hypothesis testing, probability distributions, and
correlation analysis.
Key Features:
1. Probability Distributions – Supports both continuous (e.g., Normal, Exponential) and
discrete (e.g., Poisson, Binomial) distributions.
2. Descriptive Statistics – Computes important statistical measures like mean, variance,
standard deviation, skewness, and kurtosis.
3. Hypothesis Testing – Includes tests such as t-tests, chi-square tests, ANOVA, and
Kolmogorov-Smirnov tests.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

4. Correlation and Regression Analysis – Measures relationships between variables using


Pearson correlation, Spearman correlation, and linear regression.
5. Random Sampling – Generates random values from different probability distributions

2) List out the important methods available in scipy.stats package.


Ans} 1. Descriptive Statistics
• mean() – Computes the mean of the data.
• median() – Finds the median value.
• mode() – Returns the most frequent value.
• var() – Calculates variance.
• std() – Computes standard deviation.
• skew() – Measures the asymmetry of data distribution.
• kurtosis() – Determines the "tailedness" of the distribution.
2. Probability Distributions
• norm.pdf(x, loc, scale) – Probability density function (PDF) for the normal distribution.
• norm.cdf(x, loc, scale) – Cumulative distribution function (CDF).
• norm.rvs(size, loc, scale) – Generates random samples from a normal distribution.
• binom.pmf(k, n, p) – Binomial probability mass function (PMF).
• poisson.pmf(k, mu) – Poisson distribution PMF.
3. Hypothesis Testing
• ttest_ind(a, b) – Performs an independent t-test for two samples.
• ttest_rel(a, b) – Performs a paired t-test.
• chisquare(f_obs, f_exp) – Performs the chi-square test.
• f_oneway(*groups) – Conducts a one-way ANOVA test.
• ks_2samp(data1, data2) – Performs the Kolmogorov-Smirnov test.

REFERENCE:

1. “SciPy and NumPy”, Eli Bressert, 2nd Edition, 2013, O’Reilly Media Inc.
2. “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.6
AIM: 1. Read a dataset of Populations of any Five States of India and give the
descriptive statistics by determining the values of mean, variance, skewness
and kurtosis for the population datasets
Name of Student: _Ronak Wanjari__
Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import pandas as pd
import scipy.stats as stats
# Load dataset from CSV
df = pd.read_csv("indian_population.csv")
# Compute Descriptive Statistics
mean_value = df["Population"].mean()
variance_value = df["Population"].var()
skewness_value = stats.skew(df["Population"])
kurtosis_value = stats.kurtosis(df["Population"])
print("Descriptive Statistics for Population Data:")
print(f"Mean: {mean_value}")
print(f"Variance: {variance_value}")
print(f"Skewness: {skewness_value}")
print(f"Kurtosis: {kurtosis_value}")

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

AIM: 2)Read the famous “Iris” dataset and give descriptive statistical analysis by
determining values of mean, variance, skewness and kurtosis. Conduct a
hypothesis testing by applying the t-tests to compare the means of any two
species.

CODE:
import pandas as pd
from scipy import stats
from sklearn.datasets import load_iris
# Load the Iris dataset
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target
# Descriptive Statistics
mean = df.mean()
variance = df.var()
skewness = df.skew()
kurtosis = df.kurtosis()
# Print Descriptive Statistics
print("Descriptive Statistics:")
print("Mean:\n", mean)
print("Variance:\n", variance)
print("Skewness:\n", skewness)
print("Kurtosis:\n", kurtosis)

# Hypothesis Testing: t-test between Setosa (species 0) and Versicolor (species 1)


setosa_petal_length = df[df['species'] == 0]['petal length (cm)']
versicolor_petal_length = df[df['species'] == 1]['petal length (cm)']
# Perform t-test
t_stat, p_value = stats.ttest_ind(setosa_petal_length, versicolor_petal_length)

# Print T-test Results


print("\nT-test Results:")
print(f"T-statistic: {t_stat:.4f}, P-value: {p_value:.4f}")

# Interpretation of the p-value


if p_value < 0.05:
print("Reject the null hypothesis: There is a significant difference between the means.")
else:
print("Fail to reject the null hypothesis: There is no significant difference between the
means.")

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 07
Aim: Import sales data of a Cosmetic Company. Analyze it through following ways with
visualizationusing Matplotlib:
a) Read the total profit of all the months and visualize it using a Line Plot.
b) Read all product sales data and show it using a Multiline Plot.
c) Read face cream and face wash product sales data and show it using theBar chart.
d) Calculate total sale data for last year for each product and show it using a Pie chart.

Name of Student: Ronak S. Wanjari


Roll No.: ET22036
Semester/Year: 6th/3rd
Academic Session: 2024-2025
Date of Performance:
Date of Submission:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with visualization techniques/plots available in pyplot package of
Matplotlib Library.
• To apply various visualization techniques available in pyplot package of
Matplotlib Library.
THEORY:

Matplotlib is a powerful library in Python used for data visualization. It provides various plotting
functions through the pyplot module, which allows users to create high-quality graphs and
charts. The pyplot module is commonly used because of its ease of use and similarity to
MATLAB’s plotting functions.

Importance of Data Visualization:

Data visualization plays a crucial role in understanding trends, patterns, and insights from raw
data. Using different types of charts and graphs, we can make data more interpretable and
visually appealing.

Visualization Techniques Used in This Practical:

1. Line Plot:

o Used to visualize the total profit across different months.

o Helps in understanding the trend of profits over time.

2. Multiline Plot:

o Displays sales trends of multiple products in the same graph.

o Useful for comparing different product performances over months.

3. Bar Chart:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

o Used to compare sales of face cream and face wash.

o Bar charts are effective for representing discrete data comparisons.

4. Pie Chart:

o Displays the total yearly sales of different products as proportions.

o Helps in understanding which product contributed the most to total sales.

By using Matplotlib, we can efficiently represent sales data, making it easier to analyze business
performance and make data-driven decisions.

FLOWCHART:

Start

Read CSV File

Plot total profit using Line Plot

Plot product sales using Multiline

Plot Face Cream vs Face Wash

Plot total yearly sales using Pie

End

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

PROGRAM:

# RONAK WANJARI
# ET22026

import pandas as pd
import matplotlib.pyplot as plt
# Load the CSV file
df = pd.read_csv('ronakcos.csv')
# Strip any leading or trailing spaces from column names
df.columns = df.columns.str.strip()
df.rename(columns={
'face Cream': 'Face Cream',
'Face Wash': 'Face Wash',
'shampoo': 'Shampoo',
'Sun cream': 'Sun Cream',
'hair Jel': 'Hair Gel',
'Conditioner': 'Conditioner',
'Lipstick': 'Lipstick'
}, inplace=True)
# (a) Line plot for total profit per month
plt.figure(figsize=(10,5))
plt.plot(df['Month'], df['Total_Profit'], marker='o', linestyle='-', color='b', label='Total Profit')
plt.xlabel('Month')
plt.ylabel('Total Profit')
plt.title('Total Profit per Month')
plt.xticks(rotation=45)
plt.legend()
plt.grid()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

plt.show()
# (b) Multiline plot for all product sales
df.set_index('Month', inplace=True)
df.plot(kind='line', figsize=(12,6), marker='o')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Sales of Different Products per Month')
plt.xticks(rotation=45)
plt.grid()
plt.show()

# (c) Bar chart for Face Cream and Face Wash sales
df[['Face Cream', 'Face Wash']].plot(kind='bar', figsize=(12,6))
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Face Cream & Face Wash Sales per Month')
plt.xticks(rotation=45)
plt.legend()
plt.show()

# (d) Pie chart for total sales of each product over the year
total_sales = df.sum()
total_sales = total_sales.drop('Total_Profit') # Excluding total profit from pie chart
total_sales.plot(kind='pie', autopct='%1.1f%%', figsize=(8,8))
plt.title('Total Sales Distribution per Product')
plt.ylabel('') # Remove y-label
plt.show

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

CONCLUSION:
Here we have successfully hands-on with visualization techniques available in pyplot package of
Matplotlib Library.

DISCUSSION QUESTIONS:
1) Determine the significance of pyplot package available in Matplotlib Library.

Ans: The pyplot module in Matplotlib is a collection of functions that make plotting easier,
similar to MATLAB. It provides a simple interface to create and customize various types of plots
such as line graphs, bar charts, histograms, and scatter plots. It helps in quickly visualizing data
without requiring detailed knowledge of the underlying plotting mechanisms.

2) List out the important methods available in pyplot package & Matplotlib.
Ans:
pyplot Methods:
• plt.plot() – Creates line plots.
• plt.bar() – Creates bar charts.
• plt.hist() – Plots histograms.
• plt.pie() – Creates pie charts.
• plt.xlabel() / plt.ylabel() – Adds labels to axes.
• plt.title() – Adds a title to the plot.
• plt.legend() – Displays a legend.
• plt.xlim() / plt.ylim() – Sets limits for axes.
• plt.grid() – Adds grid lines.
• plt.savefig() – Saves the figure to a file.
• plt.show() – Displays the plot.
Matplotlib Methods (Beyond pyplot):
• matplotlib.figure.Figure() – Creates a new figure object.
• matplotlib.axes.Axes() – Adds and customizes axes.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

• matplotlib.cm.get_cmap() – Retrieves colormaps.


• matplotlib.ticker() – Controls axis ticks.
• matplotlib.animation – Supports animated plots.

REFERENCE:

1. “Hands-on Matplotlib: Learn Plotting and Visualizations with Python 3”, Ashwin Pajankar, 1st
Edition, 2021, Kindle.

• “Python: The complete Reference”, Martin C Brown, 1st Edition, 2001, McGraw Hill

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 9
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.7
AIM: 1. Import a dataset of new recruitments in companies such as Microsoft,
Google, Amazon, IBM, Deliotte, Capmemini, ATOS Origin, Amdocs etc.
Generate & visualize reports of new recruitments using:
a) Bar Chart
b) Pie Chart
c) Customize Pie Chart
d) Doughnut Chart
Compare the new recruitments in IBM & Amdocs using visualization.
Name of Student: _Ronak Wanjari__
Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('ronaknew.csv')

# a) Bar Chart
df.plot(kind='bar', x='Company', y='Number of Hires', color='skyblue', legend=False)
plt.title('New Recruitments by Company (Bar Chart)')
plt.ylabel('Number of Hires')
plt.xticks(rotation=45)
plt.show()

# b) Pie Chart
plt.pie(df['Number of Hires'], labels=df['Company'], autopct='%1.1f%%', startangle=140,
colors=plt.cm.Paired.colors)
plt.title('New Recruitments by Company (Pie Chart)')
plt.show()

# c) Customize Pie Chart (Exploded slice for Microsoft)


explode = (0.1, 0, 0, 0, 0, 0, 0, 0)
plt.pie(df['Number of Hires'], labels=df['Company'], autopct='%1.1f%%', startangle=140,
explode=explode, colors=plt.cm.Paired.colors)
plt.title('New Recruitments by Company (Customized Pie Chart)')
plt.show()

# d) Doughnut Chart
plt.pie(df['Number of Hires'], labels=df['Company'], autopct='%1.1f%%', startangle=140,
colors=plt.cm.Paired.colors, wedgeprops={'width': 0.4})
plt.title('New Recruitments by Company (Doughnut Chart)')
plt.show()

# IBM vs Amdocs Comparison


df[df['Company'].isin(['IBM', 'Amdocs'])].plot(kind='bar', x='Company', y='Number of Hires',
color=['orange', 'green'], legend=False)
plt.title('Comparison of New Recruitments: IBM vs Amdocs')
plt.ylabel('Number of Hires')
plt.show()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

AIM:2) Import a dataset of sales last 5 years of different cars in India such as
BMW, Mercedes-Benz, Land Rover, Fortuner etc. Generate visualization
reports using 3D: a) Bar Chart b) Pie Chart c) Doughnut Chart.
Visualize the comparative sales BMW and Fortuner in last 5 years

CODE:
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
df = pd.read_csv("car_sales_data.csv")
# 3D Bar Chart
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i, brand in enumerate(df.columns[1:]):
ax.bar(df['Year'], df[brand], zs=i, zdir='y', alpha=0.8, label=brand)
ax.set(title='3D Bar Chart: Car Sales in India', xlabel='Year', ylabel='Brands', zlabel='Sales')
plt.legend()
plt.show()
# 3D Pie Chart (Using shadow effect for 3D look)
total_sales = df.iloc[:, 1:].sum()
fig, ax = plt.subplots()
ax.pie(total_sales, labels=total_sales.index, autopct='%1.1f%%', startangle=140,
colors=plt.cm.Paired.colors, shadow=True)
ax.set_title('3D Pie Chart: Total Car Sales Distribution')
plt.show()
# 3D Doughnut Chart (Using shadow effect for 3D look)
fig, ax = plt.subplots()
ax.pie(total_sales, labels=total_sales.index, autopct='%1.1f%%', startangle=140,
colors=plt.cm.Paired.colors, wedgeprops={'width': 0.4}, shadow=True)
ax.set_title('3D Doughnut Chart: Car Sales Distribution')
plt.show()
# 3D Comparative Sales: BMW vs Fortuner
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.bar(df['Year'], df['BMW'], zs=0, zdir='y', alpha=0.8, label='BMW')
ax.bar(df['Year'], df['Fortuner'], zs=1, zdir='y', alpha=0.8, label='Fortuner')
ax.set(title='3D Comparative Sales: BMW vs Fortuner', xlabel='Year', ylabel='Brands',
zlabel='Sales')
plt.legend()
plt.show()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 08
Aim: Demonstrate data manipulation and visualization by utilizing Pandas for data
manipulation and Matplotlib to create insightful visualizations.
Import a dataset related to the Scottish Hills from the file “scottish_hills.csv”.
The file “scottish_hill.csv” contains different fields such as Hill Name, Height, Latitude,
Longitude and OSGRID. Perform the following operations:
a) Display the contains of the dataset
b) Display the details of Hills in sorted order based on their heights
c) Visualize the relation between Height and Latitude using Scatter Plot
d) Apply the Linear Regression method to the Height and Latitude data and again visualize
using Scatter Plot.
e) Customize the Scatter Plot for insightful visualization.
Name of Student: Ronak S. Wanjari
Roll No.: ET22036
Semester/Year: 6th/3rd
Academic Session: 2024-2025
Date of Performance:
Date of Submission:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with data manipulation and visualization techniques available in
Python libraries Pandas & Matplotlib.
• To apply various data manipulation and visualization techniques available in
Python libraries Pandas & Matplotlib.
THEORY:

Pandas Library:
Pandas is an open-source Python library that provides data structures and functions needed to
efficiently manipulate structured data.
• It provides Series (1D) and DataFrame (2D) structures.
• It allows for data filtering, grouping, merging, and aggregation.
• Supports file formats like CSV, Excel, JSON, and SQL.
• Handles missing values and time-series data effectively.
Matplotlib Library:
Matplotlib is a Python plotting library used for visualizing data.
• Supports various plots like line, bar, scatter, histogram, and pie charts.
• Provides options for customization with labels, legends, gridlines, and styles.
• Helps in saving figures in different formats like PNG, PDF, and SVG.
• Useful for data analysis and trend visualization.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

FLOWCHART:

Start

Read dataset (scottish_hills.csv)

Print dataset

Sort dataset by Height

Plot Scatter Plot (Height vs


Latitude)

Define X = Latitude, Y = Height

Predict Height values

Plot Scatter with Regression Line

End

PROGRAM:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

data = pd.read_csv('scottish_hills.csv')
print(data)
sorted_hills = data.sort_values(by='Height', ascending=False)
print(sorted_hills)
plt.figure(figsize=(10, 6))
plt.scatter(data['Latitude'], data['Height'], color='blue', alpha=0.5)
plt.title('Scatter Plot of Height vs Latitude')
plt.xlabel('Latitude')
plt.ylabel('Height (meters)')
plt.grid(True)
plt.show()
X = data[['Latitude']]
y = data['Height']
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
plt.figure(figsize=(10, 6))
plt.scatter(data['Latitude'], data['Height'], color='green', alpha=0.5, label='Data Points')
plt.plot(data['Latitude'], y_pred, color='red', linewidth=2, label='Regression Line')
plt.title('Height vs Latitude with Linear Regression')
plt.xlabel('Latitude')
plt.ylabel('Height (meters)')
plt.legend()
plt.grid(True)
plt.show()
plt.figure(figsize=(10, 6))
# Define colors based on height, creating a color map (from blue to red based on height)
plt.scatter(data['Latitude'], data['Height'], c=data['Height'], cmap='coolwarm', s=100, alpha=0.7,
edgecolors='black')
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 4
Software Workshop Lab (PCCET605P)

plt.title('Customized Scatter Plot of Height vs Latitude', fontsize=14)


plt.xlabel('Latitude', fontsize=12)
plt.ylabel('Height (meters)', fontsize=12)
plt.colorbar(label='Height (meters)')
plt.show()
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

CONCLUSION:
Here we have successfully hands-on data manipulation and visualization techniques available in
Python libraries Pandas & Matplotlib.
DISCUSSION QUESTIONS:
1) Determine the significance of Pandas & Matplotlib Libraries of Python.

ANS: Pandas:
• Used for data manipulation and analysis.

• Provides data structures like Series (1D) and DataFrame (2D).

• Supports reading and writing data from CSV, Excel, JSON, and SQL.

• Helps in data cleaning, filtering, grouping, and analysis.

• Efficient handling of missing values and large datasets.

Matplotlib:

• Used for data visualization in Python.

• Supports various plots like line, bar, scatter, pie, histogram, etc.

• Allows customization with titles, labels, legends, and colors.

• Enables saving plots in multiple formats like PNG, PDF, and SVG.

• Helps in visualizing trends and relationships in data.

2) List out features of Pandas and Matplotlib libraries.

ANS: Pandas Features:

• Flexible Data Structures – Series (1D) & DataFrame (2D).

• Data Handling – Sorting, filtering, merging, and grouping.

• File Support – Reads/writes CSV, Excel, and databases.

• Missing Data Handling – Filling or removing missing values.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

• Handling – Filling or removing missing values.

• Time-Series Analysis – Date-time indexing and operations.

Matplotlib Features:
• Multiple Plot Types – Line, bar, pie, scatter, and histogram.

• Customization – Labels, legends, gridlines, and styles.

• Annotations & Labels – Add titles and data labels.

• Subplots & Multi-Figures – Multiple graphs in one figure.

• Exporting Options – Save figures in PNG, PDF, etc.

REFERENCE:

1. “Hands-on Matplotlib: Learn Plotting and Visualizations with Python 3”, Ashwin
Pajankar, 1st Edition, 2021, Kindle.
2. “Python for Data Analysis”, Wes McKinney, 3rd Edition, 2022, O’Reilly Media.
“Python: The complete Reference”, Martin C Brown,

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.8
AIM: Develop a program to print the data on maps using Cartopy.

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
# Create a figure and set the projection to PlateCarree
fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
# Add map features
ax.add_feature(cfeature.LAND, edgecolor='black')
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS, linestyle=':')
# Set extent (longitude, latitude limits)
ax.set_extent([-180, 180, -90, 90]) # World map
# Add sample data (example: plotting a point)
lon, lat = 79.0882, 21.1458
ax.scatter(lon, lat, color='red', transform=ccrs.PlateCarree(), label="Nagpur")
# Add title and legend
plt.title("Simple Map with Cartopy")
plt.legend()
plt.show()

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Practical No. 09
Aim: Develop a Web Application using “Streamlit” for Electronics Products.
Create a dataset related to the selling of Electronic Products at a showroom. Create a dashboard
application with following requirements:
a) Create a mechanism to upload the sales file.
b) Create a mechanism to preview the data of sales file.
c) Generate a summary of sales data
d) Create a mechanism to filter out sales details
e) Generate different plots related to sales data.

Name of Student: Ronak S. Wanjari


Roll No.: ET22036
Semester/Year: 6th/3rd
Academic Session: 2024-2025
Date of Performance:
Date of Submission:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

OBJECTIVE/EXPECTED LEARNINGOUTCOME:
The objectives and expected learning outcome of this practical are:
• To get familiar with features for developing Web Applications & Websites using
Streamlit Web Framework.
• To apply various techniques available in Streamlit for developing Web
applications and websites.
THEORY:

Streamlit is an open-source Python framework for creating interactive web applications with
minimal coding. It is widely used in data science and machine learning due to its simplicity and
fast development process.
Key Features of Streamlit:
• Python-Based: No need for HTML, CSS, or JavaScript.
• Easy UI Components: Built-in widgets like buttons, sliders, and file uploaders.
• Real-Time Updates: Automatically refreshes when the script changes.
• Data Visualization Support: Integrates with Matplotlib, Seaborn, and Plotly.
• State Management: Uses st.session_state to retain user inputs.
• Fast Deployment: Can be hosted on Streamlit Cloud, Heroku, or AWS.
Concepts Used in This Web Application:
• Uploading CSV Files: Users can upload and preview electronics product sales data.
• Data Summary & Filtering: Generates statistics and allows filtering based on selected
criteria.
• Data Visualization: Displays sales trends using Line, Bar, and Scatter plots.
Applications of Streamlit:
• Data Dashboards, Machine Learning Apps, Stock Market Analysis, and IoT Monitoring.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

FLOWCHART:

PROGRAM:

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

st.title("Ronak's Electronics Products Sales Dashboard")

uploaded_file = st.file_uploader("Upload your file", type=["csv"])


if uploaded_file is not None:
sales_data = pd.read_csv(uploaded_file)
st.success("File uploaded successfully!")

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

if st.checkbox("Preview Data"):
st.write(sales_data)

st.subheader("Sales Data Summary")


st.write(sales_data.describe())

category_filter = st.selectbox("Select Category to Filter", sales_data['Category'].unique())


filtered_data = sales_data[sales_data['Category'] == category_filter]
st.write(filtered_data)

st.subheader("Sales Data Visualization")


fig, ax = plt.subplots()
sales_data.groupby('Category')['Quantity_Sold'].sum().plot(kind='bar', ax=ax)
st.pyplot(fig)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 4
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6
Software Workshop Lab (PCCET605P)

CONCLUSION:
Here we have successfully hands-on with various techniques available in Streamlit for
developing Web applications and websites.

DISCUSSION QUESTIONS:
1) List out the significant features of Streamlit.

Ans: Streamlit is a Python-based framework for creating interactive web applications for
machine learning and data science. Key features include:
1. Simplicity & Ease of Use – Streamlit provides a minimalistic API to build UI
components using Python scripts without requiring HTML, CSS, or JavaScript.
2. Widgets for User Interaction – Offers built-in widgets like sliders, buttons, text inputs,
and dropdowns to collect user input dynamically.
3. Live Code Reloading – Automatically updates the app in real-time when the script is
modified and saved.
4. Seamless Data Visualization – Supports popular libraries like Matplotlib, Plotly,
Seaborn, and Altair for easy integration of charts and graphs.

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 7
Software Workshop Lab (PCCET605P)

5. Fast Deployment – Allows hosting and sharing of applications on platforms like


Streamlit Community Cloud with minimal setup.
6. State Management – Provides st.session_state for handling user inputs and interactions
across multiple interactions.
7. Markdown & LaTeX Support – Enables displaying formatted text, code blocks, and
equations within the app.
8. Media Support – Allows displaying images, videos, and audio files using simple
Streamlit functions.
9. Data Caching – Uses st.cache_data and st.cache_resource to optimize expensive
computations and API calls.
10. Authentication & Cloud Integration – Supports authentication methods and easy
integration with cloud platforms for scalable deployment.

2) Give comparison between features of Django and Streamlit.

Ans:

Streamlit (Data App


Feature Django (Web Framework)
Framework)

Full-stack web development Rapid development of data-


Purpose
framework driven web apps

Requires knowledge of HTML, Python-centric, no front-end


Ease of Use
CSS, JavaScript knowledge needed

Designed for large-scale


Performance Lightweight, ideal for small apps
applications

Development Slower due to full-stack Faster, focuses on rapid


Speed complexity prototyping

Uses Django ORM for database Primarily works with Pandas,


Data Handling
management NumPy, and APIs

Requires templates (HTML, CSS, Uses built-in widgets and


UI Design
JavaScript) components

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 8
Software Workshop Lab (PCCET605P)

S. B. JAIN INSTITUTE OF
TECHNOLOGY,MANAGEMENT& RESEARCH,NAGPUR.
Lab Assignment no.9
AIM: 1)Develop a Web Application using “Streamlit” for dataset of an eCommerce Website.

Name of Student: _Ronak Wanjari__


Roll No.: ET22036
Semester/Year: 6TH /3RD
Academic Session:_____________
Date of Performance:__________
Date of Submission: __________

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 1
Software Workshop Lab (PCCET605P)

CODE:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
st.title(" Simple E-Commerce Data Analysis")
# Upload CSV file
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])
if uploaded_file:
df = pd.read_csv(uploaded_file)
st.write("### Dataset Preview")
st.write(df.head())
st.write("### Dataset Summary")
st.write(df.describe())
# Choose column for histogram
numeric_columns = df.select_dtypes(include=['number']).columns.tolist(
if numeric_columns:
column = st.selectbox("Select a column for histogram", numeric_columns)
fig, ax = plt.subplots()
ax.hist(df[column], bins=20, color='blue', edgecolor='black')
ax.set_title(f"Histogram of {column}")
st.pyplot(fig)
else:
st.info("Please upload a CSV file.")
OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 2
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 3
Software Workshop Lab (PCCET605P)

AIM2: Develop a Web Application based on the study of heart diseases for a
Hospital

CODE:
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
st.title(" Simple Heart Disease Analysis")
# Upload CSV file
uploaded_file = st.file_uploader("Upload Heart Disease Data (CSV)", type=["csv"])
if uploaded_file:
df = pd.read_csv(uploaded_file)
st.write("### Dataset Preview")
st.write(df.head())
st.write("### Summary Statistics")
st.write(df.describe())
# Select numeric column for visualization
numeric_columns = df.select_dtypes(include=['number']).columns.tolist()
if numeric_columns:
column = st.selectbox("Select a column for histogram", numeric_columns)
fig, ax = plt.subplots()
ax.hist(df[column], bins=20, color='red', edgecolor='black')
ax.set_title(f"Histogram of {column}")
st.pyplot(fig)
else:
st.info("Please upload a CSV file.")
Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,
Nagpur. 4
Software Workshop Lab (PCCET605P)

OUTPUT:

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 5
Software Workshop Lab (PCCET605P)

Department of Electronics and Telecommunication Engineering, S.B.J.I.T.M.R,


Nagpur. 6

You might also like