PIYUSH_PythonLABmanual
PIYUSH_PythonLABmanual
L. D. College of Engineering
LABORATORY MANUAL
MCA
Semester II
Year 2024-25
Piyushkumar V Sharma
(245160694029)
L. D. College of Engineering
Ahmedabad
Page | 2
Government of Gujarat
L. D. College of Engineering
Date: _______________
Page | 3
Government of Gujarat
L. D. College of Engineering
INDEX
Program Name: Master of Computer Applications
Semester: 2
Subject: Programming In Python (MC02094051)
1 | Page
12.Write a program in python to implement
Factorial series up to user entered number. (Use
recursive Function).
13.Write a program to display all prime numbers
within a range
14.Given a range of the first 10 numbers, Iterate
from the start number to the end number, and In
each iteration print the sum of the current
number and previous number
15.Given a two list of numbers create a new list
such that new list should contain only odd
numbers from the first list and even numbers
from the second list
Practical2: File Operation
Practical 4: Exceptions
2 | Page
5. Write a Python program that executes an
operation on a list and handles an IndexError
exception if the index is out of range.
6. Write a Python program that executes division
and handles an ArithmeticError exception if there
is an arithmetic error.
7. 7. Write a Python program that executes a list
operation and handles an AttributeError
exception if the attribute does not exist.
Practical 5: OOP Concepts
3 | Page
5. a string that has an a followed by two to three
'b'.
6. find sequences of lowercase letters joined with a
underscore.
7. find the sequences of one upper case letter
followed by lower case letters.
8. matches a string that has an 'a' followed by
anything, ending in 'b'.
9. matches a word at the beginning of a string.
10.matches a word containing 'z', not at the start or
end of the word.
11.match a string that contains only upper and
lowercase letters, numbers, and underscores.
12.string will start with a specific number
13.to check for a number at the end of a string.
14.to search the numbers (0-9) of length between 1
to 3 in a given string
15.to convert a date of yyyy-mm-dd format to
dd-mm-yyyy format. For Specific Data Entered
16.to find all words starting with 'a' or 'e' in a given
string.
17.program to separate and print the numbers and
their position of a given string.
18.To check Valid email address
19.Valid PAN CARD Details
Practical 7 Data Visulization
4 | Page
Practical 9: Database Application
Read a CSV File (use Pract 7)
With Operations
Web Scraping
10
Read a website (with tabular data) as HTML and
perform basic tabular data analysis as practical 7
5 | Page
Practical 1
AIM: Basics of Python
Programs
1. Write a Python Program to Convert Celsius to Fahrenheit and vice –a-versa.
Code:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
def main():
while True:
print("\nTemperature changing Program !")
print("1. Convert Celsius to Fahrenheit !")
print("2. Convert Fahrenheit to Celsius !")
print("3. Exit out from your Code !")
choice = int(input("\nEnter your choice amoung {1, 2, 3} : "))
if(choice == 1):
celsius = float(input("Enter the temperature in Celsius : "))
print(f"{celsius} C is equal to {celsius_to_fahrenheit(celsius):.2f} F.")
elif(choice == 2):
fahrenheit = float(input("Enter the temperature in Fahrenehit : "))
print(f"{fahrenheit} F is equal to {fahrenheit_to_celsius(fahrenheit):.2f} C.")
elif(choice == 3):
print("Terminating .....")
print("Terminated Successfully")
exit()
else:
print("We Dont have any other options!\nPlease choose amoung 1, 2 or 3.")
if __name__ == "__main__":
main()
Output:
1 | Page
2. Write a program in python to swap two variables without using temporary variable.
Code :
num1 = 10
num2 = 20
# Method 1
num1, num2 = num2, num1
print("\nValues after Swapping ! USING METHOD 1")
print(f"Value of num1 is : {num1}\nValue of num2 is : {num2}")
Output:
3. Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal.
Code :
2 | Page
print("The Decimal Number you Entered is :", decimal)
print(bin(decimal), " is in Binary Format")
print(oct(decimal), " is in Octal Format")
print(hex(decimal), " is in Hexadecimal Format\n")
Output :
3 | Page
4. Write a program to make a simple calculator (using functions).
Code :
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "Error! Division by zero."
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")
if choice in ['1', '2', '3', '4']:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# ... perform operation
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input! Please enter 1, 2, 3, or 4.")
Output :
4 | Page
5. Write a program in python to find out maximum and minimum number out of three user entered
number.
Code :
Output :
6. Write a program which will allow user to enter 10 numbers and display largest odd number from
them. It will display appropriate message in case if no odd number is found.
Code :
Output:
5 | Page
7. Write a Python program to check if the number provided by the user is an Armstrong
number.
Code :
Output :
8. Write a Python program to check if the number provided by the user is a palindrome or not.
Code :
6 | Page
print("Entered Number is not a Palindrome Number !")
Output :
9. Write a Python program to perform following operation on given string input:
a) Count Number of Vowel in given string b) Count Length of string (do not use Len ())
c) Reverse string d) Find and replace operation e) check whether string entered is a
palindrome or not
Code :
while True:
print("\na. Count Number of Vowels in a given String.")
print("b. Count Length of string (do not use Len ()).")
print("c. Reverse a String.")
print("d. Find and replace operation.")
print("e. Check whether string entered is a palindrome or not")
print("f. Enter F/f to Exit from the Program !\n")
if(choice == 'f'):
exit()
match choice:
case "a":
vowels = ["a", "e", "i", "o", "u"]
word = input("Enter any String : ")
print("Your String is : " + word)
count = 0
for i in word:
if i in vowels:
count += 1
print("Number of Vowels in your String are :", count, "\n")
case "b":
count = 0
word = input("Enter any String : ")
for i in word:
count += 1
print("The Length of the String \"" + word + "\" is :", count, "\n")
case "c":
# Method 1
word = input("Enter any String : ")
rev = ""
for count in word:
7 | Page
rev = count + rev
print("the reversed String is : ", rev, "\n")
# Method 2
# word = input("Enter any String : ")[::-1]
# print("The Reversed String is : ", word, "\n")
# Method 3
# word = input("Enter any String : ")
# def rev(word):
# return word[::-1]
# print("The reversed String is : ", rev(word), "\n")
case "d":
word = input("Enter any String : ").lower()
find_word = input("Enter the String you want to Find : ").lower()
replace_word = input("Enter the String to want to replace with : ").lower()
ans = word.replace(find_word, replace_word) #how to find and replace without
replace() function !?
print("The String after find and replace is : ", ans, "\n")
case "e":
word = input("Enter any String : ").lower()
rev_word = word[::-1]
if word == rev_word:
print("Entered String is a Palindrome String !", "\n")
else:
print("Entered String is not a Palindrome String !", "\n")
Output :
10.Define a procedure histogram () that takes a list of integers and prints a histogram to the
screen. For example, histogram ([4, 9, 7]) should print the following: **** ********* *******
Code :
def histogram():
num = int(input("\nEnter the no. of Elements in a list you want : "))
8 | Page
li = []
for i in range(num):
user_input = int(input("Enter the Number to enter in a list : "))
li.append(user_input)
print("Your Entered List of Numbers are :", li)
print("Histogram of the Given numbers in a list are given below !")
for i in li:
print(i * "*")
histogram()
Output :
11.Write a program in python to implement Fibonacci series up to user entered number. (Use
recursive Function)
Code :
def fibonacci(user_input):
if user_input <= 0:
return 0
elif user_input == 1:
return 1
else:
return fibonacci(user_input - 1) + fibonacci(user_input - 2)
user_input = int(input("Enter a Number of Elements to be shown in a Fibonacci Series : "))
for i in range(user_input):
print(fibonacci(i), end=" ")
Output :
9 | Page
12.Write a program in python to implement Factorial series up to user entered number. (Use
recursive Function).
Code :
def factorial(user_input):
if user_input < 0:
return "Can not Find the Factorial of a Negative Number !"
elif user_input == 0 or user_input == 1:
return 1
else:
return user_input * factorial(user_input - 1)
user_input = int(input("Enter a Number to find its Factorial : "))
fact = 0
for i in range(user_input + 1):
fact = factorial(i)
print(f"The Factorial of {user_input} is : {fact}")
Output :
Code :
user_input = int(input("Enter the Upper Limit to find the Prime Number : "))
10 | Page
for num in range(2,user_input):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print (num, "is a Prime Number !")
Output :
14.Given a range of the first 10 numbers, Iterate from the start number to the end number, and
In each iteration print the sum of the current number and previous number
Code :
Output :
11 | Page
15.Given a range of the first 10 numbers, Iterate from the start number to the end number, and
In each iteration print the sum of the current number and previous number
Code :
l1 = [1, 2, 3, 4, 5]
l2 = [6, 7, 8, 9, 0]
l3 = []
for i in l1:
if i % 2 == 1:
l3.append(i)
for j in l2:
if j == 0:
continue
elif j % 2 == 0:
l3.append(j)
print("The First List :", l1)
print("The Second List :", l2)
print("The Below list Contains only Odd Numbers from the First List and Even Numbers
from the Second List.\n", l3)
Output :
********************
12 | Page
Practical 2
Write a program to open/close file with read/write mode and implement following functions:
Program
Code :
print("\n1. To copy content of one file to another.\n2. To Capitalize word of File each copy
content of one file to another.\n3. Display Distinct Characters and their counts, No of Words,
No of Lines in a File.")
print("-" * 100)
# Task 3
print("\nExecuting Task No. 3 ........")
distinct_char = {}
for char in content:
13 | Page
if char.isalpha():
distinct_char[char] = distinct_char.get(char, 0) + 1
words = content.split()
word_count = len(words)
lines = content.split("\n")
line_count = len(lines)
Output :
15 | Page
*********
Practical 3
Write a program to open/close file with read a paragraph from file and perform following tasks:
1. Return the count of sub-string {pattern} appears in the given file
2. Reverse Every Word of File
3. Remove the {a,e,i,o,u} from the words of File Replace Every Character a-z by z-a(reverse order, aàz,
bày, …)
Program
Code :
print("\n1. Return the count of sub-string {pattern} appears in the given file")
print("2. Reverse Every Word of File")
print("3. Remove vowels (a, e, i, o, u) and replace letters a-z with their reverse counterpart\n")
paragraph = []
paragraphs = []
16 | Page
readF1 = open("./text.txt", "r")
# Task no. 1
print("Executing Task no. 1 .....")
pattern = input("\nEnter the Pattern to count it in a Paragraph : ").lower()
print("\nReading Pattern from the Single Paragraph.....")
para_text = "".join(paragraph).lower()
count = para_text.count(pattern)
print(f"The Pattern \'{pattern}\' has appered {count} time in a single Paragraph !")
# Task no. 2
print("\nExecuting Task no. 2 .....")
def reverse_words(text):
return " ".join(word[::-1] for word in text.split())
17 | Page
print("\nReversing the Single Paragraph !\n")
if paragraph:
print(reverse_words(paragraph[0]))
# Task no 3
print("\nExecuting Task no. 3 .....")
def transform_text(text):
vowel_removed = ""
for char in text:
if char.lower() not in "aeiou":
vowel_removed += char
transformed_text = ""
for char in vowel_removed:
if char.isalpha(): # Only transform letters
if 'a' <= char <= 'z': # Lowercase letters
new_char = chr(219 - ord(char))
elif 'A' <= char <= 'Z': # Uppercase letters
new_char = chr(155 - ord(char))
else:
new_char = char # Keep other characters unchanged
else:
new_char = char # Keep non-alphabetic characters unchanged
transformed_text += new_char
return transformed_text
# Example Usage
# paragraph = ["Hello World! 123"]
print("\nExecuting Single Paragraph...\n")
print(transform_text(paragraph[0]))
print()
18 | Page
print("Task no. 3 completed!\n")
# print("-" * 100)
readF1.close()
Output :
19 | Page
*********
20 | Page
Practical 4
Program
Code :
try:
# num1 = float(input("Enter numerator: "))
# num2 = float(input("Enter denominator: "))
num1 = 10
num2 = 0
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Output :
2. Write a Python program that prompts the user to input an integer and raises a ValueError
exception if the input is not a valid integer.
Code :
try:
# user_input = int(input("Enter an integer: "))
user_input = input("Enter an integer: ")
number = int(user_input)
print("You entered a valid integer:", user_input)
except ValueError:
print("Error: Invalid input! Please enter a valid integer.")
Output :
21 | Page
3 Write a Python program that opens a file and handles a FileNotFoundError exception if the
file does not exist.
Code :
Output :
4. Write a Python program that prompts the user to input two numbers and raises a TypeError
exception if the inputs are not numerical.
Code :
try:
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
if not (num1.replace('.', '', 1).isdigit() and num2.replace('.', '', 1).isdigit()):
# if not (num1.isdigit() and num2.isdigit()):
# raise TypeError("Inputs must be whole numbers (integers only).")
22 | Page
raise TypeError("Inputs must be numeric.")
num1 = float(num1)
num2 = float(num2)
# num1 = int(num1)
# num2 = int(num2)
print("Sum:", num1 + num2)
except TypeError as e:
print("Error:", e)
Output :
5. Write a Python program that executes an operation on a list and handles an IndexError
exception if the index is out of range.
Code :
Output :
23 | Page
6. Write a Python program that executes division and handles an ArithmeticError exception if
there is an arithmetic error.
Code :
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ArithmeticError as ae:
print("Arithmetic Error occurred:", ae)
except ValueError:
print("Error: Please enter valid whole numbers only.")
Output :
7. Write a Python program that executes a list operation and handles an AttributeError
exception if the attribute does not exist.
Code :
24 | Page
numbers = [10, 5, 0, 3, 3]
for i in range(len(numbers) - 1):
try:
result = numbers[i] / numbers[i + 1]
print(f"Division result: {result}")
except ArithmeticError as e:
print(f"ArithmeticError occurred: {e}")
Output :
********
Practical 5
Program
Code :
class Vehicle:
pass
# Creating an object of Vehicle class
v1 = Vehicle()
# Output just to show object is created
print("Vehicle object created:", v1)
Output :
2. Create a Vehicle class with max_speed and mileage instance attributes
Code :
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
25 | Page
self.mileage = mileage
# Creating an object with values
v1 = Vehicle(120, 15000)
# Printing values
print("Max Speed:", v1.max_speed)
print("Mileage:", v1.mileage)
Output :
3. Create a child class Bus that will inherit all of the variables and methods of the Vehicle class
Code :
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
# Child class inheriting from Vehicle
class Bus(Vehicle):
pass
# Creating an object of Bus
bus1 = Bus(80, 12000)
# Printing inherited attributes
print("Bus Max Speed:", bus1.max_speed)
print("Bus Mileage:", bus1.mileage)
Output :
26 | Page
4. Create a Bus class that inherits from the Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.
Code :
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
# Child class Bus
class Bus(Vehicle):
def seating_capacity(self, capacity=50):
return f"The seating capacity of the bus is {capacity} passengers."
# Example usage
bus1 = Bus(90, 15000)
print("Max Speed:", bus1.max_speed)
print("Mileage:", bus1.mileage)
print(bus1.seating_capacity()) # Default value
print(bus1.seating_capacity(60)) # Custom value
Output :
5. Define property that should have the same value for every class instance
Code :
class Vehicle:
# Class variable (shared by all instances)
color = "White"
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage
# Creating instances
v1 = Vehicle("Car", 120, 15000)
27 | Page
v2 = Vehicle("Bus", 80, 25000)
# Accessing the class variable
print(f"Vehicle 1: {v1.name}, Color: {v1.color}")
print(f"Vehicle 2: {v2.name}, Color: {v2.color}")
Output :
6. Create a Bus child class that inherits from the Vehicle class. The default fare charge of any
vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on
full fare as a maintenance charge. So total fare for bus instance will become the final amount
= total fare + 10% of the total fare.
Code :
class Vehicle:
def __init__(self, name, seating_capacity):
self.name = name
self.seating_capacity = seating_capacity
def fare(self):
return self.seating_capacity * 100
class Bus(Vehicle):
def fare(self):
base_fare = super().fare()
maintenance_charge = base_fare * 0.10 # 10% extra
total_fare = base_fare + maintenance_charge
return total_fare
28 | Page
# Example
vehicle = Vehicle("Car", 10)
print(f"Total Car Fare is : Rs. {vehicle.fare()}")
bus = Bus("School Bus", 50)
print(f"Total Bus Fare (with maintenance): Rs. {bus.fare()}")
Output :
7. Determine which class a given Bus object belongs to (Check type of an object)
Code :
class Vehicle:
pass
# class Bus: # False !
# pass
class Bus(Vehicle):
pass
# Creating a Bus object
my_bus = Bus()
# Checking the type of the object
print("The type of the object is:", type(my_bus))
# Verifying if it is an instance of Bus
print("Is my_bus an instance of Bus?", isinstance(my_bus, Bus))
# Verifying if it is also an instance of Vehicle (parent class)
print("Is my_bus an instance of Vehicle?", isinstance(my_bus, Vehicle))
Output :
Code :
class Vehicle:
pass
class Bus(Vehicle):
pass
class SchoolBus(Bus):
pass
29 | Page
# Creating an instance of SchoolBus
school_bus = SchoolBus()
# Check if school_bus is an instance of Vehicle
print("Is school_bus an instance of Vehicle?", isinstance(school_bus, Vehicle))
Output :
30 | Page
Practical 6
Write a program to generate data of 500 randomly generated printable characters[a-z,A-Z, Special Chars, 0-9, etc,
spaces/blanks ] and perform the following operations
Program
Code :
import re
import random
import string
31 | Page
print("15. Converted Date:", new_date)
# Task 16: words starting with 'a' or 'e'
print("16.", re.findall(r'\b[aeAE]\w*', data))
# Task 17: numbers and their positions
for match in re.finditer(r'\d+', data):
print("17. Number:", match.group(), "at position", match.start())
# Task 18: valid email check in sample
sample_text = "My email is [email protected]\nMy email is [email protected]"
print("18.", re.findall(r'\b[\w.-]+@[\w.-]+\.\w{2,4}\b', sample_text))
# Task 19: valid PAN (e.g., ABCDE1234F)
pan_data = "My PAN is ABCDE1234F\nMy PAN is XYZYX1001P"
print("19.", re.findall(r'\b[A-Z]{5}[0-9]{4}[A-Z]\b', pan_data))
Output :
32 | Page
Practical 7
Python for Data Visualization Library: pylab, matplotlib, seaborn , Consider Suitable Data
Bar Graph
Histogram
Pie-Chart
Line Chart
Bubble Chart
Scatter Chart
Program
Code :
Output :
33 | Page
2. Histogram :
Output :
34 | Page
3. Pie-Chart :
Output :
35 | Page
4. Line Chart :
Output :
36 | Page
5. Bubble Chart :
Output :
38 | Page
Practical 8
b. Operations on Data Frame Shape, head, tail c. Retrieving rows / columns from data frame
f. Performing queries
Program
p8_data.csv (Sample Data) :
Code :
A. Create DataFrame :
import pandas as pd
import pandas as pd
# Load data from CSV (assuming 'students.csv' is already created)
df = pd.read_csv("./p8_data.csv")
# 1. Get the shape of the DataFrame (rows, columns)
print("Shape of the DataFrame:", df.shape)
# 2. Get the first 5 rows (head)
print("\nFirst 5 rows using head():\n", df.head())
# 3. Get the last 5 rows (tail)
print("\nLast 5 rows using tail():\n", df.tail())
Output :
import pandas as pd
# Load CSV
df = pd.read_csv("./p8_data.csv")
# Print the entire DataFrame
print("Full DataFrame:\n", df)
# Retrieve specific column (e.g., 'Name')
print("\nColumn 'student_id':\n", df['student_id'])
# Retrieve multiple columns
print("\nColumns 'student_id' and 'Age':\n", df[['student_id', 'age']])
# Retrieve specific row using iloc (e.g., first row)
40 | Page
print("\nFirst row:\n", df.iloc[0])
# Retrieve multiple rows (first three)
print("\nFirst three rows:\n", df.iloc[0:3])
# Retrieve specific rows and columns
print("\nFirst 2 rows of 'student_id' column:\n", df.loc[0:1, 'student_id'])
Output :
import pandas as pd
# Load the CSV file
df = pd.read_csv('p8_data.csv')
# Display max and min for each column (numeric only)
print("Maximum values in each column:")
print(df.max(numeric_only=True))
print("\nMinimum values in each column:")
print(df.min(numeric_only=True))
Output :
41 | Page
E. Displaying Statistical Information :
import pandas as pd
# Load the CSV file
df = pd.read_csv('p8_data.csv')
# Display statistical information
print("Statistical Information:")
print(df.describe())
Output :
import pandas as pd
#1.) Employees with Age > 30
df = pd.read_csv('./p8_data.csv')
print("\n", df[df['age'] > 30])
#2.) Employees in 'IT' Department
print("\n", df[df['mental_health_rating'] == 'Poor'])
#3.) Using query() method — Salary > 50000
print("\n", (df.query('exam_score > 50')))
# 4. Combined Query — Age < 40 and Department is 'HR'
print("\n", df.query("age < 40 and mental_health_rating == 'Average'"))
Output :
42 | Page
G. Data Analysis using groupby():
import pandas as pd
# Read the CSV file
df = pd.read_csv("p8_data.csv")
# Group by Subject and calculate average marks
average_exam_score = df.groupby('mental_health_rating')['exam_score'].mean()
print("Average exam_score by mental_health_rating:")
print(average_exam_score)
# Group by mental_health_rating and count number of students
student_count = df.groupby('mental_health_rating')['student_id'].count()
print("\nNumber of Students per mental_health_rating:")
print(student_count)
# Group by mental_health_rating and find maximum exam_score
max_exam_score = df.groupby('mental_health_rating')['exam_score'].max()
print("\nMaximum exam_score by mental_health_rating:")
print(max_exam_score)
Output :
43 | Page
H. Handling Missing Data:
import pandas as pd
44 | Page
'Subject': 'Unknown'
})
print("\nDataFrame after Filling Missing Values:\n")
print(df_filled)
Output :
45 | Page
Practical 9
Write functions for inserting Numeric Columns and Label Data Columns in to Database
With Operations
b) modify a record
c) display a record
d) delete a record
h) Create Web Database Application “Event Registration” with options to a) Event Registration b) Cancel
Registration c) display a record
Program
File Structure :
Code :
import sqlite3
import pandas as pd
# Close connection
conn.close()
47 | Page
Output :
import sqlite3
# Close connection
conn.close()
48 | Page
Output :
import sqlite3
Output :
49 | Page
D) Delete a Record :
import sqlite3
if record:
print(f"\nRecord to be deleted for student_id {student_id}:")
print(record)
# Example usage
delete_record('S1004') # Replace with your target student_id
Output :
50 | Page
E) Export data to CSV File After Operarions :
import sqlite3
import pandas as pd
Output :
import sqlite3
import pandas as pd
# Connect to the database
conn = sqlite3.connect('students.db')
# Load data into DataFrame
df = pd.read_sql_query("SELECT * FROM students", conn)
# Convert DataFrame to HTML and save to file
html_output = "students_table.html"
✅
df.to_html(html_output, index=False)
print(f" HTML table saved as '{html_output}'")
51 | Page
# Close connection
conn.close()
Output :
import csv
# File name
filename = 'p9_data.csv'
# Open and read the CSV file
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile)
print("Reading CSV file...\n")
for row in reader:
print(f"Student ID: {row['student_id']}, Exam Score: {row['exam_score']}, Gender:
{row['gender']}")
Output :
52 | Page
H) Create Web Database Application “Event Registration” woth Options to
a) Event Registration
b) Cancel registration
c) Display a Record
app.py :
53 | Page
def cancel():
email = request.form['email']
conn = sqlite3.connect('event.db')
cursor = conn.cursor()
cursor.execute('DELETE FROM registrations WHERE email = ?', (email,))
conn.commit()
conn.close()
return redirect('/')
# Display Registrations
@app.route('/display')
def display():
conn = sqlite3.connect('event.db')
cursor = conn.cursor()
cursor.execute('SELECT * FROM registrations')
rows = cursor.fetchall()
conn.close()
return render_template('display.html', rows=rows)
if __name__ == '__main__':
init_db()
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head><title>Event Registration</title></head>
<body>
<h2>Register for Event</h2>
<form action="/register" method="post">
Name: <input type="text" name="name" required><br>
Email: <input type="email" name="email" required><br>
Event Name: <input type="text" name="event" required><br>
<input type="submit" value="Register">
</form>
<h2>Cancel Registration</h2>
<form action="/cancel" method="post">
Email: <input type="email" name="email" required><br>
<input type="submit" value="Cancel">
</form>
<h2><a href="/display">View All Registrations</a></h2>
</body>
</html>
display.html
<!DOCTYPE html>
<html>
<head><title>All Registrations</title></head>
<body>
<h2>Registered Participants</h2>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Email</th><th>Event</th></tr>
54 | Page
{% for row in rows %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
</tr>
{% endfor %}
</table>
<br><a href="/">Back to Home</a>
</body>
</html>
Output :
55 | Page
56 | Page
Practical 10
Web Scraping
Read a website(with tabular data ) as HTML and perform basic tabular data analysis as practical 7
Program
File Structure :
Code :
● App.py:
from flask import Flask, render_template, request
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from bs4 import BeautifulSoup
import requests
from io import BytesIO
import base64
app = Flask(__name__)
sns.set(style="whitegrid")
chart_types = [
'Bar Chart', 'Pie Chart', 'Histogram', 'Line Chart',
'Bubble Chart', 'Scatter Plot', 'Heatmap', 'Box Plot'
]
def scrape_data():
url = 'https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'class': 'wikitable'})
df = pd.read_html(str(table))[0]
df = df[['Location', 'Population', '% of world', 'Date']]
df.columns = ['Country', 'Population', 'World_Percent', 'Date']
df = df.head(10)
df['Population'] = df['Population'].astype(str).str.replace(r'[^0-9]', '', regex=True).astype(float)
57 | Page
df['World_Percent'] = df['World_Percent'].astype(str).str.replace('%', '',
regex=False).astype(float)
df['Population_Millions'] = df['Population'] / 1_000_000
return df
buf = BytesIO()
plt.tight_layout()
plt.savefig(buf, format='png')
buf.seek(0)
chart_base64 = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
return chart_base64
● templates/interactive_dashboard.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Interactive Population Dashboard</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="container">
<h1>Interactive World Population Dashboard</h1>
<div class="chart-box">
<img src="data:image/png;base64,{{ chart }}" alt="Selected Chart">
</div>
<div class="table-section">
<h2>Scraped Population Data</h2>
{{ table|safe }}
</div>
</div>
</body>
</html>
● static/style.css :
.dropdown-form {
margin-bottom: 30px;
text-align: center;
animation: fadeIn 1.5s ease-in-out;
}
select, button {
padding: 10px;
margin: 5px;
font-size: 16px;
border: 2px solid #4CAF50;
border-radius: 5px;
background-color: #f9f9f9;
transition: all 0.3s ease;
59 | Page
cursor: pointer;
}
select:hover, button:hover {
background-color: #4CAF50;
color: white;
transform: scale(1.1);
}
button:active {
transform: scale(0.95);
background-color: #45a049;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
How to Run
1. Save the files in the structure above.
2. In terminal:
cd web_dashboard
python app.py
3. Open http://127.0.0.1:5000/ in your browser
60 | Page
Output :
● Data table :
61 | Page