0% found this document useful (0 votes)
9 views

PIYUSH_PythonLABmanual

The document is a laboratory manual for the MCA Semester II course on Programming with Python at L. D. College of Engineering, detailing various practical exercises and coding tasks. It includes topics such as basic Python programming, file operations, string operations, exception handling, object-oriented programming, regular expressions, data visualization, data analytics, database applications, and web scraping. The manual serves as a guide for students to complete their laboratory work as part of their course requirements.

Uploaded by

sarthakvadhel1
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 views

PIYUSH_PythonLABmanual

The document is a laboratory manual for the MCA Semester II course on Programming with Python at L. D. College of Engineering, detailing various practical exercises and coding tasks. It includes topics such as basic Python programming, file operations, string operations, exception handling, object-oriented programming, regular expressions, data visualization, data analytics, database applications, and web scraping. The manual serves as a guide for students to complete their laboratory work as part of their course requirements.

Uploaded by

sarthakvadhel1
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/ 69

​ Government of Gujarat

L. D. College of Engineering

LABORATORY MANUAL

MCA

Semester II

Programming with Python


(MC02094051)

Year 2024-25

Piyushkumar V Sharma
(245160694029)

L. D. College of Engineering
Ahmedabad

Page | 2
Government of Gujarat
L. D. College of Engineering

This is to certify that Mr. PIYUSHKUMAR V SHARMA


Enrollment No. 245160694029 of Semester II Information
Technology has successfully completed the prescribed term
work/laboratory work of Programing With Python course within
the four walls of L. D. College of Engineering. This is required as a
partial fulfillment of the said course of Gujarat Technological
University.

Date: _______________

Course In-Charge​ ​ ​ External Examiner

Page | 3
Government of Gujarat
L. D. College of Engineering

INDEX
Program Name: Master of Computer Applications
Semester: 2
Subject: Programming In Python (MC02094051)

Sr No Topic Page No Date Sign


Practical 1: Basics of Python

1.​ Write a Python Program to Convert Celsius to


Fahrenheit and vice –a-versa.
2.​ Write a program in python to swap two variables
without using temporary variable.
3.​ Write a Python Program to Convert Decimal to
Binary, Octal and Hexadecimal
4.​ Write a program to make a simple calculator
(using functions).
5.​ Write a program in python to find out maximum
and minimum number out of three user entered
number.
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.
1
7.​ Write a Python program to check if the number
provided by the user is an Armstrong number.
8.​ Write a Python program to check if the number
provided by the user is a palindrome or not.
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
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: **** ********* *******
11.​Write a program in python to implement
Fibonacci series up to user entered number. (Use
recursive Function)

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

Write a program to open/close file with read/write


mode and implement following functions:

2 1.​ To copy content of one file to another


2.​ To Capitalize word of File each copy content of
one file to another
3.​ Display Distinct Characters and their counts, No
of Words, No of Lines in a File.

Practical 3: String Operationsē

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


3
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, …)

Practical 4: Exceptions

1.​ Write a Python program to handle a


ZeroDivisionError exception when dividing a
number by zero.
2.​ Write a Python program that prompts the user to
input an integer and raises a ValueError exception
4 if the input is not a valid integer.
3.​ Write a Python program that opens a file and
handles a FileNotFoundError exception if the file
does not exist.
4.​ Write a Python program that prompts the user to
input two numbers and raises a TypeError
exception if the inputs are not numerical.

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

1.​ Create a Vehicle class without any variables


and methods
2.​ Create a Vehicle class with max_speed and
mileage instance attributes
3.​ Create a child class Bus that will inherit all of
the variables and methods of the Vehicle class
4.​ Create a Bus class that inherits from the
Vehicle class. Give the capacity argument of
Bus.seating_capacity() a default value of 50.
5.​ Define property that should have the same
5 value for every class instance
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.
7.​ Determine which class a given Bus object
belongs to (Check type of an object)
8.​ Determine if School_bus is also an instance of
the Vehicle class.

Practical 6 Regular Expression

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.

Search the instance of patterns


6
1.​ matches a string that has an a followed by zero
or more b's.
2.​ matches a string that has an a followed by one or
more b's
3.​ matches a string that has an a followed by zero
or one 'b'
4.​ matches a string that has an a followed by two
'b'

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

Python for Data Visualization Library: pylab,


matplotlib, seaborn, Consider Suitable Data

7 1.​ Bar Graph


2.​ Histogram
3.​ Pie-Chart
4.​ Line Chart
5.​ Bubble Chart
6.​ Scatter Chart
Practical 8: Data Analytics

Perform following operations on a CSV file

1.​ Create a data frame from csv file, dictionary, List


of tuples
2.​ Operations on Data Frame Shape, head, tail
8 3.​ Retrieving rows / columns from data frame
4.​ Finding maximum and minimum values
5.​ Displaying statistical information
6.​ Performing queries
7.​ Data Analysis using groupby()
8.​ Handling missing data (NA, Missing,Null)

Use Kaggle Datasets

4 | Page
Practical 9: Database Application

Read a CSV File (use Pract 7)

Write functions for inserting Numeric Columns and


Label Data Columns in to Database

With Operations

1.​ add/ insert a record


2.​ modify a record
9 3.​ display a record
4.​ delete a record
5.​ Export data to CSV File After Operations
6.​ Represent as HTML Table
7.​ Write a program to process CSV file using CSV
module.
8.​ Create Web Database Application “Event
Registration” with options to
a) Event Registration
b) Cancel Registration
c) display a record
Practical 10: Web Scraping

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

print("\nValues before Swapping !")


print(f"Value of num1 is : {num1}\nValue of num2 is : {num2}")

# 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 :

decimal = int(input("\nEnter any Number : "))

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 :

def max(x, y, z):


if x > y and x > z:
print("The Maximum Number amoung the Given Three Number is :", x)
elif y > z:
print("The Maximum Number amoung the Given Three Number is :", y)
else:
print("The Maximum Number amoung the Given Three Number is :", z)

def min(x, y, z):


if (x < y and x < z):
print("The Minimum Number amoung the Given Three Number is :", x)
elif y < z:
print("The Minimum Number amoung the Given Three Number is :", y)
else:
print("The Minimum Number amoung the Given Three Number is :", z)

one = int(input("Enter The First Number : "))


two = int(input("Enter The Second Number : "))
three = int(input("Enter The Three Number : "))
max(one, two, three)
min(one, two, three)

​ 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 :

num = [int(input("Enter The Number : ")) for _ in range(10)]


odd_num = list(filter(lambda x: x % 2 == 1, num))
if odd_num:
print("The Largest Odd Number is : ", max(odd_num))
else:
print("No Odd number Found !")

​ Output:

5 | Page
7.​ Write a Python program to check if the number provided by the user is an Armstrong
number.
​ Code :

num = int(input("Enter the Number : "))


og_num = num
sum = 0
digits = len(str(num))
def checkArmstrong(num, digits, sum):
if(num == 0):
return sum
sum += pow(int(num % 10), digits)
return checkArmstrong(num //10, digits, sum)
if checkArmstrong(num, digits, sum) == num:
print("The Entered Number is an Armstrong Number!")
else:
print("The Entered Number is not an Armstrong Number!")

​ Output :

8.​ Write a Python program to check if the number provided by the user is a palindrome or not.

​ Code :

num = int(input("Enter the Number : "))


og_num = num
rev_num = 0
length = len(str(og_num))
while og_num > 0:
rev_num = (rev_num * 10) + (og_num % 10)
og_num //= 10
if(num == rev_num):
print("Entered Number is a Palindrome Number !")
else:

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")

choice = input("Enter Your choice[a, b, c, d, e, f] : ").strip().lower()

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 :

13.​Write a program to display all prime numbers within a range

​ 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 :

for num in range(10):


# print(num)
sum = 0
previousNumber, currentNumber = num, num + 1
sum = previousNumber + currentNumber
print(f"The Sum of Previous number {previousNumber} + Current Number
{currentNumber} is : {sum}")
previousNumber, currentNumber = currentNumber, currentNumber + 1

​ 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

AIM: File Operation

Write a program to open/close file with read/write mode and implement following functions:

1.​ To copy content of one file to another


2.​ To Capitalize word of File each copy content of one file to another
3.​ Display Distinct Characters and their counts, No of Words, No of Lines in a File.

Program
​ Code :

readF1 = open("./one.txt", "r")


# print("\nReading the Content of the File one.txt...\n")
content = readF1.read()
# print(content)

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)

for char, count in sorted(distinct_char.items()):


print(f"{char} : {count}")

print("\nTotal Number of Words are :", word_count)


print("Total Number of Lines are :", line_count)

print("\nTask No. 3 Completed !")


print("\n","-" * 100)
# Task 2
print("\nExecuteing Task Number 2 .....")
print("\nCapitalizing the Content of the file one.txt to capitalizeOne.txt....")
writeF2 = open("./capitalizeOne.txt", "w")
# capitalizeContent = content.capitalize()
capitalizeContent = content.title()
writeF2.write(capitalizeContent)
print("Content Capitalized Successfully !")
print("\nClosing The File capitalizeOne.txt after Write operation...")
writeF2.close()
print("The File capitalizeOne.txt is Closed after Write operation.")
print("\nTask No. 2 Completed !")
print("\n", "-" * 100)
# Task 1
print("\nExecuteing Task Number 1 .....")
print("\nCoping the Content of the file one.txt to copyOne.txt....")
writeF1 = open("./copyOne.txt", "w")
writeF1.write(content)
print("Copied Successfully !")
print("\nClosing The File copyOne.txt after Write operation...")
writeF1.close()
print("The File copyOne.txt is Closed after Write operation.")

print("\nClosing The File one.txt ...")


readF1.close()
print("The File one.txt is Closed.")

readF2 = open("./copyOne.txt", "r")


# print("\nReading the Content of the File copyOne.txt...\n")
copiedContent = readF2.read()
# print(copiedContent)

print("\nClosing The File copyOne.txt ...")


readF2.close()
14 | Page
print("The File copyOne.txt is Closed.")
print("\nTask No. 1 Completed !\n")
print("-" * 100, "\n")

​ Output :

15 | Page
*********

Practical 3

AIM: String Operations

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")

# readF1 = open(r"D:\Piyush\MCA\SEM_2\PythonPracticals\practical3\text.txt", "r")

for line in readF1:


if line.strip():
paragraph.append(line.strip())
else:
if paragraph:
paragraphs.append(" ".join(paragraph))
paragraph = []
if paragraph:
paragraphs.append(" ".join(paragraph))

# Reading the Last Paragraph and the List of Paragraphs !


# print()
# print("The Paragraph is :", paragraph)
# print()
# print("-" * 100)
# print()
# count = 1
# for i in paragraphs:
# print(f"Paragraph no {count} in Paragraphs list is :", i, end="\n\n")
# count += 1

# 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 !")

print("\nReading Pattern from the Multiple Paragraphs.....")


count = 0
for para in paragraphs:
count += para.lower().count(pattern)
print(f"The Pattern \'{pattern}\' has appered {count} time from Multiple Paragraphs !")
print("\nTask no. 1 completed !\n")
print("-" * 100)

# 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]))

print("\nReversing the Multiple Paragraphs !\n")


for para in paragraphs:
print(reverse_words(para), "\n")

print("\nTask no. 2 completed !\n")


print("-" * 100)

# 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()

print("Executing Multiple Paragraph... \n")


for idx, para in enumerate(paragraphs):
print(f"Transformed Paragraph {idx + 1}:")
print(transform_text(para))
print("\n" + "-" * 50 + "\n")

18 | Page
print("Task no. 3 completed!\n")
# print("-" * 100)

readF1.close()

​ Output :

19 | Page
*********

20 | Page
Practical 4

AIM: Exceptions handling

Program

1. Write a Python program to handle a ZeroDivisionError exception when dividing a number by


zero.

​ 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 :

filename = input("Enter the filename to open: ")


try:
with open(filename, "r") as file:
content = file.read()
print("File content:\n", content)
except FileNotFoundError:
print("Error: The file does not exist. Please check the file name and try again.")

​ 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 :

my_list = [10, 20, 30, 40, 50]


try:
index = int(input("Enter an index to access the list element: "))
print("Element at index", index, "is:", my_list[index])
except IndexError:
print("Error: Index is out of range. Please enter a valid index.")
except ValueError:
print("Error: Please enter a valid integer index.")

​ 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

AIM: OOP Concepts

Program

1.​ Create a Vehicle class without any variables and methods

​ 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 :

8.​ Determine if School_bus is also an instance of the Vehicle class.

​ 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

AIM: Regular Expression

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

# Generate 500 random printable characters


data = ''.join(random.choices(string.printable, k=500))
print("Generated Data:\n", data)

# Task 1 to 5: a followed by b variations


print("1.", re.findall(r'ab*', data)) # a followed by 0 or more b's
print("2.", re.findall(r'ab+', data)) # a followed by 1 or more b's
print("3.", re.findall(r'ab?', data)) # a followed by 0 or 1 b
print("4.", re.findall(r'ab{2}', data)) # a followed by exactly 2 b's
print("5.", re.findall(r'ab{2,3}', data)) # a followed by 2 to 3 b's

# Task 6: lowercase words joined with underscore


print("6.", re.findall(r'\b[a-z]+_[a-z]+\b', data))

# Task 7: one uppercase followed by lowercase


print("7.", re.findall(r'\b[A-Z][a-z]+\b', data))

# Task 8: 'a' followed by anything ending in 'b'


print("8.", re.findall(r'a.*?b', data))

# Task 9: word at beginning of string


print("9.", re.findall(r'^\w+', data))

# Task 10: word containing 'z', not at start or end


print("10.", re.findall(r'\Bz\B', data))

# Task 11: alphanumerics and underscores only


print("11.", re.findall(r'^\w+$', data)) # unlikely match unless whole string is valid

# Task 12: start with specific number (say 5)


print("12.", re.findall(r'^5', data))
# Task 13: number at end of string
print("13.", re.findall(r'\d$', data))
# Task 14: numbers 1 to 3 digits long
print("14.", re.findall(r'\b\d{1,3}\b', data))
# Task 15: convert yyyy-mm-dd to dd-mm-yyyy
date = "2025-05-05"
new_date = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\3-\2-\1', date)

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

AIM: Practical 7 Data Visulization

Python for Data Visualization Library: pylab, matplotlib, seaborn , Consider Suitable Data
​ Bar Graph

​ Histogram

​ Pie-Chart

​ Line Chart

​ Bubble Chart

​ Scatter Chart

Program

​ Code :

1.​ Bar Graph :

import matplotlib.pyplot as plt


# Sample data
subjects = ['Math', 'Physics', 'Chemistry', 'English', 'Computer']
marks = [88, 76, 90, 85, 95]
# Create a bar chart
plt.bar(subjects, marks, color='skyblue')
# Add title and labels
plt.title('Student Marks in Subjects')
plt.xlabel('Subjects')
plt.ylabel('Marks')
# Show the graph
plt.show()

​ Output :

33 | Page
2.​ Histogram :

import matplotlib.pyplot as plt


# Sample data: marks of students
marks = [55, 67, 45, 78, 90, 88, 76, 92, 56, 45, 69, 72, 80, 66, 59]
# Create histogram
plt.hist(marks, bins=5, color='orange', edgecolor='black')
# Add title and labels
plt.title('Distribution of Student Marks')
plt.xlabel('Marks')
plt.ylabel('Number of Students')
# Show the plot
plt.show()

​ Output :

34 | Page
3.​ Pie-Chart :

import matplotlib.pyplot as plt


# Sample data: Sales of different products
labels = ['Fruits', 'Vegetables', 'Dairy', 'Snacks']
sales = [150, 200, 100, 120]
colors = ['gold', 'lightgreen', 'skyblue', 'lightcoral']
# Create pie chart
plt.pie(sales, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
# Add title
plt.title('Product Sales Distribution')
# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')
# Show the plot
plt.show()

​ Output :

35 | Page
4.​ Line Chart :

import matplotlib.pyplot as plt


# Sample data: Sales of different products
labels = ['Fruits', 'Vegetables', 'Dairy', 'Snacks']
sales = [150, 200, 100, 120]
colors = ['gold', 'lightgreen', 'skyblue', 'lightcoral']
# Create pie chart
plt.pie(sales, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
# Add title
plt.title('Product Sales Distribution')
# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')
# Show the plot
plt.show()

​ Output :

36 | Page
5.​ Bubble Chart :

import matplotlib.pyplot as plt


# Sample data
x = [10, 20, 30, 40, 50] # X-axis values
y = [15, 25, 35, 45, 55] # Y-axis values
bubble_size = [100, 300, 500, 200, 400] # Bubble sizes
# Create the bubble chart
plt.scatter(x, y, s=bubble_size, alpha=0.5, c='blue', edgecolors='black')
# Add labels and title
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Simple Bubble Chart")
# Show the chart
plt.show()

​ Output :

6.​ Scatter Chart :

import matplotlib.pyplot as plt


# Sample data
x = [5, 10, 15, 20, 25, 30]
y = [2, 4, 1, 8, 7, 5]
# Create scatter plot
plt.scatter(x, y, color='green', marker='o')
# Add labels and title
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.title("Simple Scatter Chart")
# Show the chart
plt.grid(True)
plt.show()
37 | Page
​ Output :

38 | Page
Practical 8

AIM: Data Analytics

Perform following operations on a CSV file

a. Create a data frame from csv file, dictionary, List of tuples

b. Operations on Data Frame Shape, head, tail c. Retrieving rows / columns from data frame

d. Finding maximum and minimum values

e. Displaying statistical information

f. Performing queries

g. Data Analysis using groupby()

h: Handling missing data(NA, Missing,Null )

Use Kaggle Datasets

Program
​ p8_data.csv (Sample Data) :

​ Code :
A.​ Create DataFrame :

import pandas as pd

# a. Create DataFrame from CSV file


df_csv = pd.read_csv("./p8_data.csv")
print("DataFrame from CSV:\n", df_csv)

# b. Create DataFrame from Dictionary


data_dict = {
"Name": ["Amit", "Riya", "Karan"],
"Age": [21, 22, 23],
"Marks": [90, 85, 88],
"Subject": ["Physics", "Chemistry", "Math"]
}
df_dict = pd.DataFrame(data_dict)
print("\nDataFrame from Dictionary:\n", df_dict)

# c. Create DataFrame from List of Tuples


data_tuples = [
("John", 24, 91, "Biology"),
("Priya", 22, 89, "Math"),
("Sam", 20, 95, "English")
]
df_tuples = pd.DataFrame(data_tuples, columns=["Name", "Age", "Marks", "Subject"])
print("\nDataFrame from List of Tuples:\n", df_tuples)
39 | Page
​ Output :

B.​ DataFrame Shape, Head, Tail :

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 :

C.​ Retrieving Rows / Columns :

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 :

D.​ Finding Maximum and Minimum Values :

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 :

F.​ Performing Queries:

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

# Load the CSV file


df = pd.read_csv("p8_data_not_in_use.csv")
print("Original DataFrame with Missing Values:\n")
print(df)
# Check where the missing values are
print("\nMissing Values Count:\n")
print(df.isnull().sum())
# Option 1: Drop rows with any missing data
df_dropped = df.dropna()
print("\nDataFrame after Dropping Rows with Missing Values:\n")
print(df_dropped)
# Option 2: Fill missing values with a specific value
df_filled = df.fillna({
'Age': df['Age'].mean(),
'Marks': df['Marks'].mean(),

44 | Page
'Subject': 'Unknown'
})
print("\nDataFrame after Filling Missing Values:\n")
print(df_filled)

​ Output :

45 | Page
Practical 9

AIM: Practical 9: Database Application

Read a CSV File (use Pract 7)

Write functions for inserting Numeric Columns and Label Data Columns in to Database

With Operations

a) add/ insert a record

b) modify a record

c) display a record

d) delete a record

e)Export data to CSV File After Operations

f) Represent as HTML Table

g) Write a program to process CSV file using CSV module.

h) Create Web Database Application “Event Registration” with options to a) Event Registration b) Cancel
Registration c) display a record

Program
​ File Structure :

​ Code :

A.​ Add/inset a Record:

import sqlite3
import pandas as pd

# Connect to SQLite DB (or create it)


conn = sqlite3.connect('students.db')
cursor = conn.cursor()

# Drop old students table if it exists


cursor.execute("DROP TABLE IF EXISTS students")

# Create table with new schema


cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
student_id TEXT PRIMARY KEY,
age INTEGER,
gender TEXT,
study_hours_per_day REAL,
social_media_hours REAL,
netflix_hours REAL,
part_time_job TEXT,
attendance_percentage REAL,
46 | Page
sleep_hours REAL,
diet_quality TEXT,
exercise_frequency TEXT,
parental_education_level TEXT,
internet_quality TEXT,
mental_health_rating INTEGER,
extracurricular_participation TEXT,
exam_score INTEGER
)
''')

# Function to insert a record


def insert_record(row):
cursor.execute('''
INSERT INTO students (
student_id, age, gender, study_hours_per_day, social_media_hours,
netflix_hours, part_time_job, attendance_percentage, sleep_hours,
diet_quality, exercise_frequency, parental_education_level,
internet_quality, mental_health_rating, extracurricular_participation,
exam_score
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', (
row['student_id'], row['age'], row['gender'], row['study_hours_per_day'],
row['social_media_hours'], row['netflix_hours'], row['part_time_job'],
row['attendance_percentage'], row['sleep_hours'], row['diet_quality'],
row['exercise_frequency'], row['parental_education_level'],
row['internet_quality'], row['mental_health_rating'],
row['extracurricular_participation'], row['exam_score']
))
conn.commit()
print(f"Inserted record for Student ID: {row['student_id']}")

# Read CSV and insert data


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

for _, row in df.iterrows():


insert_record(row)

# View inserted data


cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
print("\nAll Records in Database:")
for row in rows:
print(row)

# Close connection
conn.close()

47 | Page
​ Output :

B)​ Modify a Record :

import sqlite3

# Connect to the database


conn = sqlite3.connect('students.db')
cursor = conn.cursor()

# --- FUNCTION TO DISPLAY RECORD BY student_id ---


def display_record(student_id, label):
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
record = cursor.fetchone()
if record:
print(f"{label} Record for student_id {student_id}:")
print(record)
else:
print(f"No record found for student_id {student_id}")
# --- FUNCTION TO MODIFY A RECORD ---
def modify_record(student_id, column_to_update, new_value):
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
old_record = cursor.fetchone()
if old_record:
display_record(student_id, "Before Update")
cursor.execute(f'''
UPDATE students
SET {column_to_update} = ?
WHERE student_id = ?
''', (new_value, student_id))
conn.commit()
print(f"\nUpdated student_id {student_id}: set {column_to_update} = {new_value}\n")
display_record(student_id, "After Update")
print("-" * 50)
else:
print(f"No record found with student_id: {student_id}")
# --- Modify and Show ---
modify_record('S1001', 'exam_score', 95)
modify_record('S1002', 'mental_health_rating', 9)

# Close connection
conn.close()

48 | Page
​ Output :

C)​ Display a Record :

import sqlite3

# Connect to the SQLite database


conn = sqlite3.connect('students.db')
cursor = conn.cursor()
# Function to display a record by student_id
def display_record(student_id):
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
record = cursor.fetchone()
if record:
print(f"\nRecord for student_id {student_id}:")
print(record)
else:
print(f"\nNo record found for student_id {student_id}")
# Example usage
display_record('S1001') # Replace with any student_id you want to check
# Close the connection
conn.close()

​ Output :

49 | Page
D)​ Delete a Record :

import sqlite3

# Connect to the SQLite database


conn = sqlite3.connect('students.db')
cursor = conn.cursor()

# Function to delete a record by student_id


def delete_record(student_id):
# Show record before deletion
cursor.execute("SELECT * FROM students WHERE student_id = ?", (student_id,))
record = cursor.fetchone()

if record:
print(f"\nRecord to be deleted for student_id {student_id}:")
print(record)

# Delete the record


cursor.execute("DELETE FROM students WHERE student_id = ?", (student_id,))
conn.commit()
print(f"\nRecord for student_id {student_id} has been deleted.")
else:
print(f"\nNo record found for student_id {student_id}")

# Example usage
delete_record('S1004') # Replace with your target student_id

# View all remaining records


print("\nRemaining records in the database:")
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
for row in rows:
print(row)

# Close the connection


conn.close()

​ Output :

50 | Page
E)​ Export data to CSV File After Operarions :

import sqlite3
import pandas as pd

# Connect to SQLite database


conn = sqlite3.connect('students.db')

# Read data from the students table into a DataFrame


df = pd.read_sql_query("SELECT * FROM students", conn)

# Export the DataFrame to a CSV file


output_csv = "exported_students_data.csv"
df.to_csv(output_csv, index=False)

print(f" ✅ Data successfully exported to '{output_csv}'")


# Close the connection
conn.close()

​ Output :

F)​ Represent an HTML Tale :

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 :

G)​ Write a Program tp process CSV File using CSV Module :

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 :

from flask import Flask, render_template, request, redirect


import sqlite3
app = Flask(__name__)
# Initialize database
def init_db():
conn = sqlite3.connect('event.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS registrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL,
event_name TEXT NOT NULL
)
''')
conn.commit()
conn.close()
# Home Page
@app.route('/')
def home():
return render_template('index.html')
# Register for Event
@app.route('/register', methods=['POST'])
def register():
name = request.form['name']
email = request.form['email']
event = request.form['event']
conn = sqlite3.connect('event.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO registrations (name, email, event_name) VALUES (?, ?, ?)',
(name, email, event))
conn.commit()
conn.close()
return redirect('/')
# Cancel Registration
@app.route('/cancel', methods=['POST'])

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

AIM: Web Scraping

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

def generate_chart(df, chart_type):


plt.figure(figsize=(10, 6))
if chart_type == 'Bar Chart':
sns.barplot(x='Population_Millions', y='Country', data=df, palette='viridis')
plt.title('Population by Country (Millions)')
elif chart_type == 'Pie Chart':
plt.pie(df['World_Percent'], labels=df['Country'], autopct='%1.1f%%')
plt.title('World Population Share')
elif chart_type == 'Histogram':
plt.hist(df['Population_Millions'], bins=5, color='orange')
plt.title('Population Histogram')
plt.xlabel('Population (Millions)')
elif chart_type == 'Line Chart':
plt.plot(df['Country'], df['Population_Millions'], marker='o')
plt.title('Line Chart - Population')
elif chart_type == 'Bubble Chart':
plt.scatter(df['Country'], df['World_Percent'], s=df['Population_Millions']*10, alpha=0.6)
plt.title('Bubble Chart: Country vs World %')
elif chart_type == 'Scatter Plot':
sns.scatterplot(x='Population_Millions', y='World_Percent', hue='Country', data=df, s=100)
plt.title('Scatter Plot: Pop vs % of World')
elif chart_type == 'Heatmap':
sns.heatmap(df[['Population', 'World_Percent']].corr(), annot=True, cmap='coolwarm')
plt.title('Correlation Heatmap')
elif chart_type == 'Box Plot':
sns.boxplot(y=df['Population_Millions'])
plt.title('Box Plot: Population')
else:
return None

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

@app.route('/', methods=['GET', 'POST'])


def dashboard():
selected_chart = request.form.get('chart') or 'Bar Chart'
df = scrape_data()
chart_image = generate_chart(df, selected_chart)
table_html = df.to_html(classes='data', index=False)
return render_template('interactive_dashboard.html',
table=table_html,
chart=chart_image,
chart_types=chart_types,
selected_chart=selected_chart)
58 | Page
if __name__ == '__main__':
app.run(debug=True)

●​ 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>

<form method="POST" class="dropdown-form">


<label for="chart">Select Chart:</label>
<select name="chart" id="chart">
{% for ct in chart_types %}
<option value="{{ ct }}" {% if ct == selected_chart %}selected{% endif %}>{{ ct
}}</option>
{% endfor %}
</select>
<button type="submit">Generate</button>
</form>

<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 :

●​ Analysis with different graphs:

61 | Page

You might also like