0% found this document useful (0 votes)
9 views44 pages

Codes

The document contains a series of Python programming tasks focused on data manipulation and visualization using pandas and matplotlib. It includes creating DataFrames for student marks and attendance, generating CSV files, plotting graphs for sales and temperature trends, and managing inventory and grocery lists. Each task is accompanied by code snippets demonstrating the implementation of the described functionalities.

Uploaded by

anshnandwana52
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)
9 views44 pages

Codes

The document contains a series of Python programming tasks focused on data manipulation and visualization using pandas and matplotlib. It includes creating DataFrames for student marks and attendance, generating CSV files, plotting graphs for sales and temperature trends, and managing inventory and grocery lists. Each task is accompanied by code snippets demonstrating the implementation of the described functionalities.

Uploaded by

anshnandwana52
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/ 44

P1).

Create a DataFrame to represent the marks of students in various


subjects. Include columns for Student_ID, Name, Subject, Marks, and
Grade. Display the row labels, column labels, data types of each column,
and the dimensions of the DataFrame.
Code import pandas as pd

# Creating the DataFrame


data = {
"Student_ID": [101, 102, 103, 104, 105],
"Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Subject": ["Math", "Science", "History", "Math", "Science"],
"Marks": [85, 90, 78, 88, 92],
"Grade": ["B", "A", "C", "B", "A"]
}

df = pd.DataFrame(data)

# Displaying the DataFrame


print("DataFrame:") print(df)

# Extracting and displaying details about the DataFrame


row_labels = df.index.tolist()
column_labels = df.columns.tolist()
data_types = df.dtypes dimensions
= df.shape

print("\nDetails:")
print(f"Row Labels: {row_labels}")
print(f"Column Labels: {column_labels}")
print("Data Types:")
print(data_types)
print(f"Dimensions: {dimensions}")
P2). Build a DataFrame to record student attendance with Student_ID, Date,
Status, and Remarks. After creating it, show the row labels, column labels,
and the data types of each column.

Code import pandas as pd

# Creating the attendance DataFrame


attendance_data = {
"Student_ID": [101, 102, 103, 104, 105],
"Date": ["2024-12-15", "2024-12-15", "2024-12-15", "2024-12-16",
"2024-12-16"],
"Status": ["Present", "Absent", "Present", "Present", "Absent"],
"Remarks": ["On time", "Sick leave", "On time", "Late",
"Personal leave"]
}

attendance_df = pd.DataFrame(attendance_data)

# Displaying the DataFrame


print("Attendance DataFrame:")
print(attendance_df)

# Extracting and displaying details about the DataFrame


row_labels = attendance_df.index.tolist() column_labels =
attendance_df.columns.tolist() data_types =
attendance_df.dtypes

print("\nDetails:")
print(f"Row Labels: {row_labels}")
print(f"Column Labels: {column_labels}")
print("Data Types:")
print(data_types)
P3). Create a CSV file named student_results.csv containing columns
Student_ID, Name, Subject, Marks, and Grade. Populate the file with at
least five records. Write a Python script to read this CSV file and display
its contents.
Code import pandas as pd

# Data to be written into the CSV file


data = {
"Student_ID": [101, 102, 103, 104, 105],
"Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Subject": ["Math", "Science", "History", "Math", "Science"],
"Marks": [85, 90, 78, 88, 92],
"Grade": ["B", "A", "C", "B", "A"]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Save the DataFrame to a CSV file


df.to_csv("student_results.csv", index=False)

# Print success message


print("CSV file 'student_results.csv' created successfully.")

# Read the CSV file and display its contents


df_read = pd.read_csv("student_results.csv")
print(df_read)
P4). Create a DataFrame with Roll_Number, Student_Name, Subject, Marks, and
Pass_Fail_Status. Write the DataFrame to a CSV file named
exam_results.csv and confirm that the file has been created successfully

Code import pandas as pd

# Data for the exam results


data = {
"Roll_Number": [1, 2, 3, 4, 5],
"Student_Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Subject": ["Math", "Science", "History", "Math", "Science"],
"Marks": [85, 90, 45, 70, 60],
"Pass_Fail_Status": ["Pass", "Pass", "Fail", "Pass", "Pass"]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Save the DataFrame to a CSV file


csv_file_path = "exam_results.csv"
df.to_csv(csv_file_path, index=False)

# Print success message


print(f"CSV file '{csv_file_path}' created successfully.")

# Display the DataFrame contents


print("\nContents of the CSV file:")
print(df)
P5). Using a dataset of student exam scores, create a bar graph to
visualize the distribution of scores. Write a Python script to generate
the plot and label the axes appropriately.

Code import matplotlib.pyplot as plt


import pandas as pd

# Sample dataset: Student names and their exam scores


data = {
"Student_Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
"Score": [85, 90, 78, 88, 92]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Create a bar graph plt.figure(figsize=(8, 6))


plt.bar(df["Student_Name"], df["Score"], color='skyblue')

# Label the axes


plt.xlabel('Student Names')
plt.ylabel('Exam Scores')
plt.title('Distribution of Student Exam Scores')

# Show the plot


plt.show()
P6). Using time series data for monthly sales figures, create a line graph to
visualize sales trends over the year. Discuss any observed trends or
patterns in your report.

Code import matplotlib.pyplot as plt


import pandas as pd

# Simulated time series data for monthly sales (in thousands


of dollars)
data = {
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec"],
"Sales": [55, 62, 70, 85, 92, 105, 98, 110, 120, 130, 140, 150]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Plot the sales data as a line graph


plt.figure(figsize=(10, 6))
plt.plot(df["Month"], df["Sales"], marker='o', linestyle='-',
color='b')

# Add titles and labels


plt.title('Monthly Sales Trends Over the Year', fontsize=16)
plt.xlabel('Month', fontsize=12)
plt.ylabel('Sales (in Thousands)', fontsize=12)

# Display the graph


plt.grid(True)
plt.show()
P7). Create a bar chart to represent the number of students enrolled in different
subjects at your school. Use a dataset with at least five subjects. Write a
report explaining the insights derived from the chart.

Code import matplotlib.pyplot as plt


import pandas as pd

# Data for subjects and enrollment


data = {
"Subject": ["Math", "Science", "History", "English", "Art"],
"Enrollment": [120, 150, 100, 130, 80]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Plot the bar chart


plt.figure(figsize=(8, 6))
plt.bar(df["Subject"], df["Enrollment"], color='skyblue',
edgecolor='black')

# Add titles and labels


plt.title("Number of Students Enrolled in Different
Subjects", fontsize=16)
plt.xlabel("Subjects", fontsize=12)
plt.ylabel("Number of Students", fontsize=12)

# Display the chart


plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()
P8). Using a dataset of student scores in a recent examination,
construct a histogram to visualize the distribution of scores.
Describe how the histogram helps in understanding the
performance of the class.
Code import matplotlib.pyplot as plt
import pandas as pd

# Data: Scores of students in an examination


data = {
"Scores": [45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 55, 60, 65,
70, 75, 80, 85, 90, 95]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Plot the histogram


plt.figure(figsize=(8, 6))
plt.hist(df["Scores"], bins=10, color='skyblue',
edgecolor='black', alpha=0.7)

# Add titles and labels


plt.title("Distribution of Student Scores", fontsize=16)
plt.xlabel("Scores", fontsize=12)
plt.ylabel("Frequency", fontsize=12)

# Display the histogram plt.grid(axis='y',


linestyle='--', alpha=0.7) plt.show()
P9). Analyze a dataset of daily temperatures over a month. Write a script to
plot the temperature trends and identify any significant fluctuations.

Code import matplotlib.pyplot as plt


import pandas as pd
import numpy as np

# Simulated dataset: Daily temperatures (in degrees Celsius)


over a month
data = {
"Day": list(range(1, 31)),
"Temperature": [15, 16, 14, 18, 20, 21, 19, 17, 16, 22, 23, 25,
24, 26, 27,
28, 29, 31, 30, 27, 25, 23, 24, 22, 20, 19, 18, 17, 16, 15]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Plot the temperature trends


plt.figure(figsize=(10, 6))
plt.plot(df["Day"], df["Temperature"], marker='o', linestyle='-',
color='b', label="Temperature")

# Highlight significant fluctuations (defined as temperature


changes > 5°C)
df["Temp_Change"] = df["Temperature"].diff().abs() #
Calculate day-to-day temperature changes
fluctuations = df[df["Temp_Change"] > 5]

plt.scatter(fluctuations["Day"], fluctuations["Temperature"],
color='r', label="Significant Fluctuation", zorder=5)
# Add titles and labels
plt.title("Daily Temperature Trends Over a Month", fontsize=16)

plt.xlabel("Day of the Month", fontsize=12)


plt.ylabel("Temperature (°C)", fontsize=12)
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)

# Show the plot


plt.show()

# Output the days with significant fluctuations if


not fluctuations.empty:
print("Days with significant temperature fluctuations:")
print(fluctuations[["Day", "Temperature",
"Temp_Change"]])
else:
print("No significant temperature fluctuations observed.")
P10). Using a dataset of monthly sales, create a line chart to visualize sales
trends over the months. Write a brief interpretation of the chart.

Code import matplotlib.pyplot as plt


import pandas as pd

# Dataset: Monthly sales figures


data = {
"Month": ["January", "February", "March", "April", "May",
"June", "July", "August",
"September", "October", "November", "December"],
"Sales": [4500, 4700, 5200, 5800, 6000, 6200, 6100,
6300, 5900, 5600, 5700, 6000]
}

# Create a DataFrame
df = pd.DataFrame(data)

# Plot the sales trends


plt.figure(figsize=(10, 6))
plt.plot(df["Month"], df["Sales"], marker='o', linestyle='-',
color='blue', label="Sales")

# Add title and labels


plt.title("Monthly Sales Trends", fontsize=16)
plt.xlabel("Month", fontsize=12)
plt.ylabel("Sales (in USD)", fontsize=12)

# Rotate x-axis labels for better readability


plt.xticks(rotation=45)
# Add a legend and grid
plt.legend()
plt.grid(True, linestyle='--', alpha=0.7)

# Show the plot


plt.tight_layout()
plt.show()
P11). ) Inventory Management: Write a program to maintain an inventory for a
store using a list of dictionaries. Each dictionary should contain Product
Name, Product ID, Quantity, and Price. Tasks: 1). Allow the user to add new
products to the inventory. 2). Create a function to calculate the total value
of the inventory (sum of Quantity × Price for each product).

Code # Inventory Management System

# Initial inventory
inventory = [
{"Product Name": "Laptop", "Product ID": 101, "Quantity":
10, "Price": 700},
{"Product Name": "Phone", "Product ID": 102, "Quantity":
20, "Price": 300},
{"Product Name": "Tablet", "Product ID": 103, "Quantity":
15, "Price": 400},
]

# Function to add a new product to the inventory


def add_product():
print("\n--- Add a New Product ---")
product_name = input("Enter product name: ")
product_id = int(input("Enter product ID: "))
quantity = int(input("Enter product quantity: "))
price = float(input("Enter product price: "))

# Add the new product to the inventory


inventory.append({
"Product Name": product_name,
"Product ID": product_id,
"Quantity": quantity,
"Price": price,
})
print(f"Product '{product_name}' added successfully!")
# Function to calculate the total value of the inventory
def calculate_total_value():
total_value = sum(item["Quantity"] * item["Price"] for item in
inventory)
return total_value

# Function to display the inventory


def display_inventory():
print("\n--- Current Inventory ---")
print(f"{'Product Name':<15}{'Product ID':<12}{'Quantity':
<10}{'Price':<10}")
print("-" * 50)
for item in inventory:
print(f"{item['Product Name']:<15}{item['Product ID']:<12}
{item['Quantity']:<10}{item['Price']:<10.2f}")

# Main program
while True:
print("\n--- Inventory Management Menu ---")
print("1. View Inventory")
print("2. Add Product")
print("3. Calculate Total Inventory Value")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":
display_inventory()
elif choice == "2":
add_product()
elif choice == "3":
total_value = calculate_total_value() print(f"\nTotal
Inventory Value: ${total_value:.2f}") elif choice ==
"4":
print("Exiting Inventory Management System. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
P12). Write a program to manage a grocery list using a dictionary. Each item
should have a name, quantity, and price. Tasks: 1). Allow the user to add
items to the grocery list. 2). Create a function to remove items from the list.
3). Calculate and display the total cost of all items in the grocery list

Code # Grocery List Management

# Initial grocery list (dictionary)


grocery_list = {}

# Function to add an item to the grocery list


def add_item():
print("\n--- Add Item to Grocery List ---")
name = input("Enter item name: ")
if name in grocery_list:
print(f"Item '{name}' already exists in the list. Updating
quantity.")
quantity = int(input(f"Enter additional quantity for
'{name}': "))
grocery_list[name]["quantity"] += quantity
else:
quantity = int(input("Enter quantity: "))
price = float(input("Enter price per unit: "))
grocery_list[name] = {"quantity": quantity, "price": price}
print(f"Item '{name}' added/updated successfully!")

# Function to remove an item from the grocery list


def remove_item():
print("\n--- Remove Item from Grocery List ---")
name = input("Enter item name to remove: ") if
name in grocery_list:
del grocery_list[name]
print(f"Item '{name}' removed successfully!")
else:
print(f"Item '{name}' not found in the grocery list!")

# Function to calculate the total cost of the grocery list

def calculate_total_cost():
total_cost = sum(item["quantity"] * item["price"] for
item in grocery_list.values())
return total_cost

# Function to display the grocery list


def display_grocery_list():
print("\n--- Grocery List ---")
if not grocery_list:
print("The grocery list is empty.")
else:
print(f"{'Item Name':<15}{'Quantity':<10}{'Price per
Unit':<15}{'Total Cost':<10}") print("-" * 50)

for name, details in grocery_list.items():


total_cost = details["quantity"] * details["price"]
print(f"{name:<15}{details['quantity']:<10}
{details['price']:<15.2f}{total_cost:<10.2f}")

# Main program
while True:
print("\n--- Grocery List Menu ---")
print("1. View Grocery List")
print("2. Add Item")
print("3. Remove Item")
print("4. Calculate Total Cost")
print("5. Exit")
choice = input("Enter your choice: ")

if choice == "1":
display_grocery_list()
elif choice == "2":
add_item()
elif choice == "3":
remove_item()
elif choice == "4":
total_cost = calculate_total_cost()
print(f"\nTotal Cost of Grocery List:
${total_cost:.2f}")
elif choice == "5":
print("Exiting Grocery List Management. Goodbye!")
break
else:
print("Invalid choice! Please try again.")
P13). Write a program that prompts the user to enter information about their
favorite books (e.g., Title, Author, Genre, Year Published). Tasks: 1). Collect
the data and write it to a new CSV file named favorite_books.csv. 2).
Display a message confirming that the data has been saved

Code import csv

# File name for storing favorite books


csv_file = "favorite_books.csv"

# Collect book information from the user


def collect_book_data():
print("\n--- Enter Information About Your Favorite Book ---
")
title = input("Enter the book title: ")
author = input("Enter the author's name: ")
genre = input("Enter the book's genre: ") year_published =
input("Enter the year the book was
published: ")

return {"Title": title, "Author": author, "Genre": genre,


"Year Published": year_published}

# Save the book data to a CSV file


def save_to_csv(book_data):
# Check if the file already exists to decide whether to write
the header
try:
file_exists = open(csv_file, "r")
file_exists.close() write_header
= False
except FileNotFoundError:
write_header = True
# Append the book data to the CSV file
with open(csv_file, "a", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["Title",
"Author", "Genre", "Year Published"])
if write_header:
writer.writeheader()
writer.writerow(book_data)

# Main program
if __name__ == "__main__":
while True:
book_data = collect_book_data()
save_to_csv(book_data)
print(f"\nThe book '{book_data['Title']}' has been
saved to '{csv_file}' successfully!")

# Ask if the user wants to add another book


another = input("Do you want to add another book?
(yes/no): ").strip().lower()
if another != "yes":
print("Thank you for using the Favorite Books
Program. Goodbye!")
break
P14). Line Graph of Temperature Changes: Create a CSV file with daily
temperature readings for a month (columns: Date and Temperature). Tasks:
1). Write a program to read the CSV file. 2). Use Matplotlib to create a line
graph showing temperature changes over the month. 3). Add grid lines and
labels for the x and y axes.

Code Create a CSV file named temperature_data.csv with two


columns: Date and Temperature. Below is a sample dataset
for one month (30 days)
Date,Temperature
2024-12-01,15
2024-12-02,14
2024-12-03,13
2024-12-04,15
2024-12-05,16
2024-12-06,17
2024-12-07,16
2024-12-08,14
2024-12-09,12
2024-12-10,10
2024-12-11,11
2024-12-12,13
2024-12-13,14
2024-12-14,16
2024-12-15,18
2024-12-16,17
2024-12-17,15
2024-12-18,14
2024-12-19,13
2024-12-20,12
2024-12-21,10
2024-12-22,11
2024-12-23,13
2024-12-24,14
2024-12-25,16
2024-12-26,17
2024-12-27,18
2024-12-28,16
2024-12-29,14
2024-12-30,12

import pandas as pd
import matplotlib.pyplot as plt

# 1. Read the CSV file


data = pd.read_csv('D:\\New Folder\\temperature_data.csv')

# 2. Create a line graph


plt.figure(figsize=(10, 6))
plt.plot(data['Date'], data['Temperature'], marker='o')

# 3. Add grid lines and labels


plt.grid(True)
plt.xlabel('Date')
plt.ylabel('Temperature')
plt.title('Temperature Changes Over the Month')

# Rotate x-axis labels for better readability (optional)


plt.xticks(rotation=45)

plt.show()
P15). Histogram of Exam Scores: You have a CSV file containing students’ exam
scores. Tasks: 1). Write a program to read the CSV file. 2). Create a
histogram to visualize the distribution of scores. 3). Label the axes and
provide a title for the histogram.
import pandas as pd
import matplotlib.pyplot as plt
Code

# 1. Read the CSV file


data = pd.read_csv('D:\\New Folder\\exam_scores.csv')

# 2. Create a histogram
plt.hist(data['score'], bins=10, edgecolor='black')

# 3. Add labels and title


plt.xlabel('score') plt.ylabel('Number of
Students') plt.title('Distribution of
Exam Scores')

plt.show()
P16). Create a DataFrame to represent the sales data of different products in
various regions. Include columns for Product_ID, Product_Name, Region,
Sales_Quantity, and Sales_Amount. Display the row labels, column labels,
data types of each column, and the dimensions of the DataFrame

import pandas as pd
Code
# Sample data
data = {'Product_ID': [101, 102, 103, 104, 105],
'Product_Name': ['Laptop', 'Smartphone', 'Tablet',
'Headphones', 'Smartwatch'],
'Region': ['East', 'West', 'South', 'North', 'Central'],
'Sales_Quantity': [100, 150, 80, 200, 120],
'Sales_Amount': [10000, 15000, 8000, 20000, 12000]}

# Create a DataFrame df
= pd.DataFrame(data)

# Display row labels


print("Row Labels:")
print(df.index)

# Display column labels


print("\nColumn Labels:")
print(df.columns)

# Display data types of each column


print("\nData Types:")
print(df.dtypes)

# Display dimensions of the DataFrame


print("\nDimensions:") print(df.shape)
P17). Create a CSV file named "product_sales.csv" containing columns
Product_ID, Product_Name, Region, Sales_Quantity, and
Sales_Amount. Populate the file with at least five records. Write a
Python script to read this CSV file and calculate the total sales for
each product.
import pandas as pd
Code import csv

# Create a list of dictionaries to represent the data


data = [
{'Product_ID': 101, 'Product_Name': 'Laptop', 'Region':
'East', 'Sales_Quantity': 100, 'Sales_Amount': 10000},
{'Product_ID': 102, 'Product_Name': 'Smartphone', 'Region':
'West', 'Sales_Quantity': 150, 'Sales_Amount': 15000},
{'Product_ID': 103, 'Product_Name': 'Tablet', 'Region':
'South', 'Sales_Quantity': 80, 'Sales_Amount': 8000},
{'Product_ID': 104, 'Product_Name': 'Headphones',
'Region': 'North', 'Sales_Quantity': 200, 'Sales_Amount':
20000},
{'Product_ID': 105, 'Product_Name': 'Smartwatch', 'Region':
'Central', 'Sales_Quantity': 120, 'Sales_Amount': 12000}
]

# Create a DataFrame from the data


df = pd.DataFrame(data)

# Save the DataFrame as a CSV file


df.to_csv('product_sales.csv', index=False)

print("CSV file 'product_sales.csv' created successfully!")

# Read the CSV file


df = pd.read_csv('product_sales.csv')

# Calculate the total sales for each product


total_sales = df.groupby('Product_ID')['Sales_Amount'].sum()

print(total_sales)
P18). Using a dataset of customer purchase data, create a line graph to visualize
the trend of sales over time. Write a Python script to generate the plot and
label the axes appropriately

import pandas as pd
Code import matplotlib.pyplot as plt

# Sample dataset (replace with your actual data)


data = {'Date': ['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-
04', '2023-01-05'],
'Sales': [100, 150, 80, 200, 120]}

# Create a DataFrame from the data


df = pd.DataFrame(data)

# Convert the 'Date' column to datetime format


df['Date'] = pd.to_datetime(df['Date'])

# Set the 'Date' column as the index


df.set_index('Date', inplace=True)

# Plot the sales trend


plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Sales'])

# Add labels and title


plt.xlabel('Date')
plt.ylabel('Sales') plt.title('Sales
Trend Over Time')

# Rotate x-axis labels for better readability


plt.xticks(rotation=45)

plt.grid(True)
plt.show()
P19). Using a dataset of customer purchase data, create a Bar Graph to visualize
the relationship between customer age and purchase amount. Write a
Python script to generate the Bar Graph and label the axes appropriately

import pandas as pd
Code import matplotlib.pyplot as plt

# Sample dataset (replace with your actual data)


data = {'Age': [25, 30, 35, 40, 45],
'Purchase_Amount': [100, 150, 80, 200, 120]}

# Create a DataFrame from the data


df = pd.DataFrame(data)

# Create a bar graph


plt.bar(df['Age'], df['Purchase_Amount'])

# Add labels and title


plt.xlabel('Age') plt.ylabel('Purchase
Amount') plt.title('Purchase Amount
by Age')

plt.show()
P20). Using a dataset of customer satisfaction ratings, create a histogram
to visualize the distribution of ratings. Write a brief interpretation of
the histogram.

import pandas as pd
Code import matplotlib.pyplot as plt

# Sample dataset (replace with your actual data)


data = {'Rating': [4, 5, 3, 2, 5, 4, 3, 5, 4, 3]}

# Create a DataFrame from the data


df = pd.DataFrame(data)

# Create a histogram
plt.hist(df['Rating'], bins=5, edgecolor='black')

# Add labels and title


plt.xlabel('Rating')
plt.ylabel('Frequency')
plt.title('Distribution of Customer Satisfaction Ratings')

plt.show()
P21). Create a table Students with columns Student_ID, Name, and Marks.
Calculate the average marks of students and retrieve students
scoring above average.

-- Step 1: Create the Students table


Code CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(100), Marks
INT
);

-- Step 2: Insert sample data into the Students table INSERT


INTO Students (Student_ID, Name, Marks) VALUES (1,
'Alice', 85),
(2, 'Bob', 75), (3,
'Charlie', 95), (4,
'David', 65), (5,
'Eva', 80);

-- Step 3: Calculate the average marks


SELECT AVG(Marks) AS Average_Marks FROM Students;

-- Step 4: Retrieve students scoring above the average marks


SELECT *
FROM Students
WHERE Marks > (SELECT AVG(Marks) FROM Students);
P22). Create tables Customers and Orders for an e-commerce platform.
Insert data and retrieve customer orders totaling over $100

-- Step 1: Create the Customers table


CREATE TABLE Customers (
Customer_ID INT PRIMARY KEY,
Code Name VARCHAR(100),
Email VARCHAR(100)
);

-- Step 2: Create the Orders table


CREATE TABLE Orders (
Order_ID INT PRIMARY KEY,
Customer_ID INT,
Order_Total DECIMAL(10, 2),
Order_Date DATE,
FOREIGN KEY (Customer_ID) REFERENCES
Customers(Customer_ID)
);

-- Step 3: Insert data into the Customers table


INSERT INTO Customers (Customer_ID, Name, Email) VALUES

(1, 'Alice', '[email protected]'),


(2, 'Bob', '[email protected]'),
(3, 'Charlie', '[email protected]');

-- Step 4: Insert data into the Orders table


INSERT INTO Orders (Order_ID, Customer_ID, Order_Total,
Order_Date) VALUES
(101, 1, 150.00, '2024-12-01'),
(102, 2, 50.00, '2024-12-02'),
(103, 1, 200.00, '2024-12-03'),
(104, 3, 75.00, '2024-12-04'),
(105, 2, 120.00, '2024-12-05');
-- Step 5: Retrieve customer orders totaling over $100
SELECT
C.Name AS Customer_Name,
C.Email AS Customer_Email,
O.Order_ID, O.Order_Total,
O.Order_Date

FROM
Customers C
JOIN Orders
O ON

C.Customer_ID = O.Customer_ID
WHERE
O.Order_Total > 100;
P23). Create a table Products with columns Product_ID, Name, Price, and
Category. Retrieve products priced between $50-$100.

-- Step 1: Create the Products table


CREATE TABLE Products (
Product_ID INT PRIMARY KEY,
Code Name VARCHAR(100),
Price DECIMAL(10, 2),
Category VARCHAR(50)
);

-- Step 2: Insert data into the Products table


INSERT INTO Products (Product_ID, Name, Price, Category)
VALUES
(1, 'Wireless Mouse', 25.99, 'Electronics'),
(2, 'Bluetooth Speaker', 65.50, 'Electronics'),
(3, 'Office Chair', 95.00, 'Furniture'),
(4, 'Table Lamp', 45.00, 'Home Decor'),
(5, 'Running Shoes', 85.99, 'Sports');

-- Step 3: Retrieve products priced between $50 and $100


SELECT *
FROM Products
WHERE Price BETWEEN 50 AND 100;
P24). Create a table called Flights with columns Flight_ID, Departure,
Arrival, and Fare. Retrieve flights departing after 6 PM

-- Step 1: Create the Flights table


CREATE TABLE Flights (
Flight_ID INT PRIMARY KEY,
Code Departure TIME,
Arrival TIME,
Fare DECIMAL(10, 2)
);

-- Step 2: Insert data into the Flights table


INSERT INTO Flights (Flight_ID, Departure, Arrival, Fare)
VALUES
(1, '14:30:00', '17:00:00', 150.00),
(2, '18:15:00', '20:30:00', 200.00),
(3, '21:00:00', '23:45:00', 180.00),
(4, '06:00:00', '08:30:00', 120.00),
(5, '16:45:00', '19:15:00', 170.00);

-- Step 3: Retrieve flights departing after 6 PM


SELECT *
FROM Flights
WHERE Departure > '18:00:00';
P25). Create tables Teachers and Classes for a school management system.
Insert data and retrieve teachers assigned to more than
two classes.
-- Step 1: Create the Teachers table
CREATE TABLE Teachers (
Teacher_ID INT PRIMARY KEY,
Code Name VARCHAR(100), Subject
VARCHAR(50)
);

-- Step 2: Create the Classes table


CREATE TABLE Classes (
Class_ID INT PRIMARY KEY,
Class_Name VARCHAR(50),
Teacher_ID INT,
FOREIGN KEY (Teacher_ID) REFERENCES
Teachers(Teacher_ID)
);

-- Step 3: Insert data into the Teachers table


INSERT INTO Teachers (Teacher_ID, Name, Subject) VALUES
(1, 'Alice', 'Mathematics'),
(2, 'Bob', 'Science'),
(3, 'Charlie', 'History');

-- Step 4: Insert data into the Classes table


INSERT INTO Classes (Class_ID, Class_Name, Teacher_ID)
VALUES
(101, 'Grade 6', 1),
(102, 'Grade 7', 1),
(103, 'Grade 8', 1),
(104, 'Grade 6', 2),
(105, 'Grade 7', 2),
(106, 'Grade 8', 3);
-- Step 5: Retrieve teachers assigned to more than two
classes
SELECT
T.Teacher_ID,
T.Name,
T.Subject,
COUNT(C.Class_ID) AS Total_Classes
FROM
Teachers T
JOIN
Classes C
ON
T.Teacher_ID = C.Teacher_ID
GROUP BY
T.Teacher_ID, T.Name, T.Subject
HAVING
COUNT(C.Class_ID) > 2;
P26). Order Management*
Create two tables, Orders and Customers.
Orders: - Order_ID (Primary Key) - Customer_ID (Foreign Key) -
Order_Date - Total_Amount
Customers: - Customer_ID (Primary Key) - Name - Email – Phone Insert
5 customers and 10 orders. Retrieve orders for each customer

Code -- Step 1: Create the Customers table


CREATE TABLE Customers (
Customer_ID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100),
Phone VARCHAR(20)
);

-- Step 2: Create the Orders table


CREATE TABLE Orders (
Order_ID INT PRIMARY KEY,
Customer_ID INT, Order_Date
DATE, Total_Amount
DECIMAL(10, 2),
FOREIGN KEY (Customer_ID) REFERENCES
Customers(Customer_ID)
);

-- Step 3: Insert data into the Customers table


INSERT INTO Customers (Customer_ID, Name, Email, Phone)
VALUES
(1, 'Alice', '[email protected]', '123-456-7890'),
(2, 'Bob', '[email protected]', '234-567-8901'),
(3, 'Charlie', '[email protected]', '345-678-9012'),
(4, 'David', '[email protected]', '456-789-0123'),
(5, 'Eva', '[email protected]', '567-890-1234');

-- Step 4: Insert data into the Orders table


INSERT INTO Orders (Order_ID, Customer_ID, Order_Date,
Total_Amount) VALUES
(1, 1, '2024-12-01', 150.00),
(2, 1, '2024-12-03', 200.00),
(3, 2, '2024-12-02', 50.00),
(4, 2, '2024-12-04', 120.00),
(5, 3, '2024-12-05', 180.00),
(6, 3, '2024-12-06', 75.00),
(7, 4, '2024-12-07', 220.00),
(8, 4, '2024-12-08', 300.00),
(9, 5, '2024-12-09', 90.00),
(10, 5, '2024-12-10', 135.00);

-- Step 5: Retrieve orders for each customer


SELECT
C.Name AS Customer_Name,
C.Email AS Customer_Email,
O.Order_ID, O.Order_Date,
O.Total_Amount

FROM
Customers C
JOIN Orders
O ON

C.Customer_ID = O.Customer_ID
ORDER BY
C.Name, O.Order_Date;
P27). Employee Department* Create two tables, Employees and
Departments. Employees: - Employee_ID (Primary Key) -
Department_ID (Foreign Key) - Name – Salary
Departments: - Department_ID (Primary Key) - Department_Name -
Location Insert 5 departments and 10 employees.
Retrieve employees by department

Code -- Step 1: Create the Departments table


CREATE TABLE Departments (
Department_ID INT PRIMARY KEY,
Department_Name VARCHAR(100),
Location VARCHAR(100)
);

-- Step 2: Create the Employees table


CREATE TABLE Employees (
Employee_ID INT PRIMARY KEY,
Department_ID INT,
Name VARCHAR(100),
Salary DECIMAL(10, 2),
FOREIGN KEY (Department_ID) REFERENCES
Departments(Department_ID)
);
-- Step 3: Insert data into the Departments table
INSERT INTO Departments (Department_ID,
Department_Name, Location) VALUES (1, 'HR', 'New York'),

(2, 'Finance', 'Chicago'),


(3, 'Engineering', 'San Francisco'),
(4, 'Marketing', 'Los Angeles'),
(5, 'Sales', 'Boston');
--Step 4: Insert data into the Employees table
INSERT INTO Employees (Employee_ID, Department_ID,
Name, Salary) VALUES
(1, 1, 'Alice', 50000.00),
(2, 1, 'Bob', 55000.00),
(3, 2, 'Charlie', 60000.00),
(4, 2, 'David', 65000.00),
(5, 3, 'Eva', 70000.00),
(6, 3, 'Frank', 75000.00),
(7, 4, 'Grace', 45000.00),
(8, 4, 'Hannah', 47000.00),
(9, 5, 'Ivy', 55000.00),
(10, 5, 'Jack', 60000.00);

-- Step 5: Retrieve employees by department


SELECT D.Department_Name,
E.Name AS Employee_Name,
E.Salary

FROM
Departments D
JOIN
Employees E
ON
D.Department_ID = E.Department_ID
ORDER BY D.Department_Name,
E.Name;
P28). Product Sales*
Create two tables, Products and Sales. Products: - Product_ID
(Primary Key) - Product_Name – Price Sales: - Sale_ID (Primary
Key) - Product_ID (Foreign Key) - Sale_Date - Quantity Insert 5
products and 10 sales. Retrieve total sales for each product.

Code -- Step 1: Create the Products table


CREATE TABLE Products (
Product_ID INT PRIMARY KEY,
Product_Name VARCHAR(100),
Price DECIMAL(10, 2)
);

-- Step 2: Create the Sales table


CREATE TABLE Sales (
Sale_ID INT PRIMARY
KEY, Product_ID INT,
Sale_Date DATE, Quantity
INT,
FOREIGN KEY (Product_ID) REFERENCES
Products(Product_ID)
);

-- Step 3: Insert data into the Products table


INSERT INTO Products (Product_ID, Product_Name, Price)
VALUES
(1, 'Laptop', 800.00),
(2, 'Smartphone', 500.00),
(3, 'Tablet', 300.00),
(4, 'Headphones', 150.00),
(5, 'Smartwatch', 200.00);
-- Step 4: Insert data into the Sales table
INSERT INTO Sales (Sale_ID, Product_ID, Sale_Date,
Quantity) VALUES
(1, 1, '2024-12-01', 3),
(2, 2, '2024-12-02', 5),
(3, 3, '2024-12-03', 2),
(4, 4, '2024-12-04', 8),
(5, 5, '2024-12-05', 4),
(6, 1, '2024-12-06', 1),
(7, 2, '2024-12-07', 3),
(8, 3, '2024-12-08', 4),
(9, 4, '2024-12-09', 6),
(10, 5, '2024-12-10', 2);

-- Step 5: Retrieve total sales for each product


SELECT
P.Product_Name,
P.Price,
SUM(S.Quantity) AS Total_Quantity_Sold,
SUM(S.Quantity * P.Price) AS Total_Sales_Amount
FROM
Products P
JOIN Sales
S ON

P.Product_ID = S.Product_ID
GROUP BY P.Product_Name,
P.Price
ORDER BY
P.Product_Name;
P29). Student Courses*
Create two tables, Students and Courses. Students: - Student_ID
(Primary Key) - Name – Department
Courses: - Course_ID (Primary Key) - Course_Name - Student_ID
(Foreign Key) Insert 5 students and 10 courses. Retrieve courses enrolled
by each student.

Code -- Step 1: Create the Students table


CREATE TABLE Students (
Student_ID INT PRIMARY KEY,
Name VARCHAR(100),
Department VARCHAR(100)
);

-- Step 2: Create the Courses table


CREATE TABLE Courses (
Course_ID INT PRIMARY KEY,
Course_Name VARCHAR(100),
Student_ID INT,
FOREIGN KEY (Student_ID) REFERENCES
Students(Student_ID)
);

-- Step 3: Insert data into the Students table


INSERT INTO Students (Student_ID, Name, Department)
VALUES
(1, 'Alice', 'Computer Science'),
(2, 'Bob', 'Mathematics'),
(3, 'Charlie', 'Physics'),
(4, 'David', 'Chemistry'),
(5, 'Eva', 'Biology');
-- Step 4: Insert data into the Courses table
INSERT INTO Courses (Course_ID, Course_Name,
Student_ID) VALUES
(1, 'Data Structures', 1),
(2, 'Algorithms', 1),
(3, 'Database Systems', 2),
(4, 'Linear Algebra', 2),
(5, 'Quantum Mechanics', 3),
(6, 'Electromagnetism', 3),
(7, 'Organic Chemistry', 4),
(8, 'Inorganic Chemistry', 4),
(9, 'Genetics', 5),
(10, 'Ecology', 5);

-- Step 5: Retrieve courses enrolled by each student


SELECT
S.Name AS Student_Name,
S.Department AS Student_Department,
C.Course_Name
FROM
Students S
JOIN
Courses C
ON
S.Student_ID = C.Student_ID
ORDER BY
S.Name, C.Course_Name;
P30). Hospital Patients*
Create two tables, Doctors and Patients.
Doctors: - Doctor_ID (Primary Key) - Name - Specialty Patients: -
Patient_ID (Primary Key) - Doctor_ID (Foreign Key) - Name -
Admission_Date

Code -- Step 1: Create the Doctors table


CREATE TABLE Doctors (
Doctor_ID INT PRIMARY KEY,
Name VARCHAR(100),
Specialty VARCHAR(100)
);

-- Step 2: Create the Patients table


CREATE TABLE Patients (
Patient_ID INT PRIMARY KEY,
Doctor_ID INT,
Name VARCHAR(100),
Admission_Date DATE,
FOREIGN KEY (Doctor_ID) REFERENCES
Doctors(Doctor_ID)
);

-- Step 3: Insert data into the Doctors table


INSERT INTO Doctors (Doctor_ID, Name, Specialty) VALUES
(1, 'Dr. Smith', 'Cardiology'),
(2, 'Dr. Johnson', 'Neurology'),
(3, 'Dr. Williams', 'Orthopedics'),
(4, 'Dr. Brown', 'Pediatrics'),
(5, 'Dr. Davis', 'Dermatology');
-- Step 4: Insert data into the Patients table
INSERT INTO Patients (Patient_ID, Doctor_ID, Name,
Admission_Date) VALUES
(1, 1, 'Alice', '2024-12-01'),
(2, 1, 'Bob', '2024-12-02'),
(3, 2, 'Charlie', '2024-12-03'),
(4, 2, 'David', '2024-12-04'),
(5, 3, 'Eva', '2024-12-05'),
(6, 3, 'Frank', '2024-12-06'),
(7, 4, 'Grace', '2024-12-07'),
(8, 4, 'Hannah', '2024-12-08'),
(9, 5, 'Ivy', '2024-12-09'),
(10, 5, 'Jack', '2024-12-10');

-- Step 5: Retrieve patients assigned to each doctor


SELECT
D.Name AS Doctor_Name,
D.Specialty AS Doctor_Specialty,
P.Name AS Patient_Name,
P.Admission_Date
FROM
Doctors D
JOIN
Patients P
ON
D.Doctor_ID = P.Doctor_ID
ORDER BY
D.Name, P.Admission_Date; Insert 5 doctors and 10 patients.
Retrieve patients assigned to each doctor

You might also like