0% found this document useful (0 votes)
72 views26 pages

Finalize

Uploaded by

baggirebel90
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)
72 views26 pages

Finalize

Uploaded by

baggirebel90
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/ 26

PROGRAM 1

Read a text file line by line and display each word separated by a #
text=open("demo.txt","r")
words=[]
for i in text:
words.extend(i.split())
print("#".join(words))
text.close()

INPUT

OUTPUT

1
PROGRAM 2
Read a text file and display the number of vowels/consonants/
uppercase/ lowercase characters in the file.
text=open("demo.txt", "r")
words=[]
vowels="aeiouAEIOU" INPUT
lines=text.readlines()
count_lower=0
count_upper=0
count_vow=0
count_cons=0
for line in lines:
words.extend(line.split())
for i in words:
for j in i:
if j in vowels:
count_vow+=1
else:
count_cons+=1
for k in i:
if k.isupper():
count_upper+=1
else:
count_lower+=1
print("number of vowels : ",count_vow)
print("number of consonants : ",count_cons)
print("number of uppercase letters : ",count_upper)
print("number of lowercase letters : ",count_lower)

OUTPUT

2
PROGRAM 3
Remove all the lines that contain the character 'a' in a file and write it to
another file.
text=open("demo.txt", "r")
read=text.readlines()
newline=[] INPUT
for i in read:
if "a" not in i:
newline.append(i)
else:
continue
result=open("output.txt", "w")
result.writelines(newline)
text.close()
result.close()

OUTPUT

3
PROGRAM 4
Create a binary file with name and roll number. Search for a given roll
number and display the name, if not found display appropriate message.
import pickle

def create_prof():
file = open("stud_roll.bin", "wb+")
n = int(input("Enter number of students: "))
for i in range(n):
dic = {}
rollno = int(input("Enter Roll number: "))
student = input("Enter Student Name: ")
dic["Roll_Number"] = rollno
dic["Student"] = student
pickle.dump(dic, file)
file.close()
print("Successfully Saved Data")

def search():
file = open("stud_roll.bin", "rb")
search_roll = int(input("Search for roll number: "))
found = False
try:
while True:
load = pickle.load(file)
if load["Roll_Number"] == search_roll:
print(load)
found = True
break
except EOFError:
if not found:
print("No Student with this roll number")
file.close()

menu = ["1. Enter Student Profile", "2. Search for Student Profile"]
for i in menu:
print(i)
while True:
choice = int(input("Enter your Choice: "))
if choice == 1:
create_prof()
elif choice == 2:
search()
else:
print("Invalid choice. Please enter a valid option.")
break

4
OUTPUT

5
PROGRAM 5
Create a binary file with roll number, name and marks. Input a roll
number and update the marks.
import pickle

def create_prof():
file = open("stud_roll.bin", "wb+")
n = int(input("Enter number of students: "))
for i in range(n):
dic = {}
rollno = int(input("Enter Roll number: "))
student = input("Enter Student Name: ")
marks = input("Enter student marks: ")
dic["Roll_Number"] = rollno
dic["Student"] = student
dic["Marks"]= marks
pickle.dump(dic, file)
file.close()
print("Successfully Saved Data")

def search():
file = open("stud_roll.bin", "rb")
search_roll = int(input("Search for roll number: "))
found = False
try:
while True:
load = pickle.load(file)
if load["Roll_Number"] == search_roll:
print(load)
found = True
subchoice=int(input("Enter 3 to update marks"))
if subchoice == 3:
upd_marks=int(input("Enter updated marks of student"))
load["Marks"]=upd_marks
print(load)
break
except EOFError:
if not found:
print("No Student with this roll number")
file.close()

menu = ["1. Enter Student Profile", "2. Search for Student Profile and update marks"]
while True:
for i in menu:
print(i)
choice = int(input("Enter your Choice: "))
if choice == 1:
6
create_prof()
elif choice == 2:
search()
else:
print("Invalid choice. Please enter a valid option.")
break
OUTPUT

7
PROGRAM 6
Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
import random
n=int(input("Enter Number of times dice thrown:"))
li=[]
for i in range(n):
a= random.randint(1,6)
li.append(a)
print("Outcomes in",n,"throws are :",li)

OUTPUT

10
PROGRAM 7
Write a Python program to implement a stack using list.

WAIT

11
PROGRAM 8
Create a CSV file by entering user-id and password, read and search
the password for given user-id.
import csv

def addincsv():
info = []
n = int(input("Enter number of users: "))
for i in range(n):
li = []
name = input("Enter name: ")
username = input("Enter username: ")
password = input("Enter password: ")
li.extend((name, username, password))
info.append(li)
with open("user.csv", "a", newline="") as data:
write = csv.writer(data)
write.writerow(["Name", "User-ID", "Password"])
write.writerows(info)

def search():
print("Enter A to search by username")
print("Enter B to search by password")
subchoice = input("Enter your choice: ").upper()

if subchoice == "A":
search_username = input("Enter username to search: ")
found = False
with open("user.csv", "r") as data:
reader = csv.reader(data)
next(reader) # Skip the header row
for row in reader:
if search_username == row[1]:
print(search_username, "is in the database")
found = True
break
if found== True:
print(search_username, "is not in the database")

elif subchoice == "B":


search_password = input("Enter password to search: ")
found = False
with open("user.csv", "r") as data:
reader = csv.reader(data)
next(reader) # Skip the header row
for row in reader:
if search_password == row[2]:
12
print(search_password, "is in the database")
found = True
break
if found== True:
print(search_password, "is not in the database")
menu = ["1. Enter Data", "2. Search Data"]
while True:
print("MENU")
print(menu[0])
print(menu[1])
choice = int(input("Enter your choice: "))
if choice == 1:
addincsv()
elif choice == 2:
search()
else:
print("Invalid Choice")
break
OUTPUT

13
PROGRAM 9
Take a sample of ten phishing e-mails (or any text file) and find most
commonly occurring word(s)
with open("phishing.txt", "r") as f:
avoid_words=['are','to','the','and','or','you','your','with','have','had','has','of','in','our','is','for','it','will']
cont=f.readlines()
text=[]
for i in cont:
text.extend(i.split(" "))
dic={}
for i in text:
if len(i)>2 and i not in avoid_words:
dic[i]=text.count(i)
for i in sorted(dic.keys()):
print(i,":",dic[i])

INPUT

OUTPUT

14
PROGRAM 10
Write a program to display unique vowels present in the given
word using Stack.
vowels="aeiouAEIOU"
word=input("Enter the word ")
stack=[]
for i in word:
if i in vowels:
if i not in stack:
stack.append(i)
print("stack :",stack)
print("VOWELS")
stack.reverse()
for i in stack:
print(i)
print("total unique vowels : ",len(stack))

INPUT

15
PROGRAM 11
Write a program that appends the contents of one file to another and
takes the filename of the new file from the user.
def content_shift(file1, file2):
try:
f1=open(f"{file1}.txt", "r")
f2=open(f"{file2}.txt", "w")
read=f1.readlines()
f2.writelines(read)
f1.close()
f2.close()
except Exception as e:
print("File not found")
input_file=input("Enter the filename from which you want to read the file")
output_file=input("Enter the filename from which you want to write the file")
content_shift(input_file,output_file)

INPUT

OUTPUT

16
PROGRAM 12
Write a program to read specific columns from a 'department.csv' file and
print the content of the columns, department ID and department name.
import csv
with open("department.csv","r") as f: INPUT
reader = csv.reader(f)
for i in reader:
print(i[0].strip(),":",i[1].strip())

OUTPUT

17
PROGRAM 13
Write a program to perform various operations on List, Tuple and
Dictionary by creating functions of each type.
def list_operations():
sample_list = [1, 2, 3, 4, 5]
while True:
print("List Operations Menu:")
print("1. Append Element")
print("2. Remove Element")
print("3. Sort List")
print("4. Find Maximum Element")
print("5. Find Minimum Element")
print("6. Display List")
print("7. Back to Main Menu")
choice = int(input("Enter your choice: "))

if choice == 1:
element = int(input("Enter element to append: "))
sample_list.append(element)
print("Updated List:", sample_list)
elif choice == 2:
element = int(input("Enter element to remove: "))
if element in sample_list:
sample_list.remove(element)
print("Updated List:", sample_list)
else:
print("Element not found in the list.")
elif choice == 3:
sample_list.sort()
print("Sorted List:", sample_list)
elif choice == 4:
print("Maximum Element:", max(sample_list))
elif choice == 5:
print("Minimum Element:", min(sample_list))
elif choice == 6:
print("Current List:", sample_list)
elif choice == 7:
break
else:
print("Invalid choice. Please try again.")

def tuple_operations():
sample_tuple = (1, 2, 3, 4, 5)
while True:
print()
print("Tuple Operations Menu:")
print("1. Access Element by Index")
print("2. Find Maximum Element") 18
print("3. Find Minimum Element")
print("4. Display Tuple")
print("5. Back to Main Menu")
choice = int(input("Enter your choice: "))

if choice == 1:
index = int(input("Enter index to access: "))
if 0 <= index < len(sample_tuple):
print("Element at index", index, ":", sample_tuple[index])
else:
print("Index out of range.")
elif choice == 2:
print("Maximum Element:", max(sample_tuple))
elif choice == 3:
print("Minimum Element:", min(sample_tuple))
elif choice == 4:
print("Current Tuple:", sample_tuple)
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")

def dictionary_operations():
sample_dict = {'a': 1, 'b': 2, 'c': 3}
while True:
print()
print("Dictionary Operations Menu:")
print("1. Add/Update Key-Value Pair")
print("2. Delete Key-Value Pair")
print("3. Get Value by Key")
print("4. Display Dictionary")
print("5. Back to Main Menu")
choice = int(input("Enter your choice: "))

if choice == 1:
key = input("Enter key: ")
value = int(input("Enter value: "))
sample_dict[key] = value
print("Updated Dictionary:", sample_dict)
elif choice == 2:
key = input("Enter key to delete: ")
if key in sample_dict:
del sample_dict[key]
print("Updated Dictionary:", sample_dict)
else:
print("Key not found.")
elif choice == 3:
key = input("Enter key to get value: ")
19
print("Value:", sample_dict.get(key, "Key not found."))
elif choice == 4:
print("Current Dictionary:", sample_dict)
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")

def main_menu():
while True:
print("Main Menu:")
print("1. List Operations")
print("2. Tuple Operations")
print("3. Dictionary Operations")
print("4. Exit")
choice = int(input("Enter your choice: "))

if choice == 1:
list_operations()
elif choice == 2:
tuple_operations()
elif choice == 3:
dictionary_operations()
elif choice == 4:
print("Exit")
break
else:
print("Invalid choice. Please try again.")

main_menu()

1
10
LIST OPERATIONS

1
11
PROGRAM 9
Create a student table and insert data
CREATE TABLE IF NOT EXISTS student (
ROLLNO INT PRIMARY KEY ,
FIRST_NAME VARCHAR(50),
1
12
SURNAME VARCHAR(50),
PHYSICS INT,
CHEMISTRY INT,
BIOLOGY INT,
MATHS INT,
COMPUTER_SCIENCE INT,
EMAIL VARCHAR(40),
CLASS int
);

#ADDING ELEMENT
INSERT INTO student(ROLLNO,FIRST_NAME,SURNAME,
PHYSICS,CHEMISTRY,BIOLOGY,MATHS,COMPUTER_SCIENCE,EMAIL,CLASS)
VALUES
(1, 'Ravi', 'Kumar', 85, 90, 88,99, 92,"[email protected]",12),
(2, 'Priya', 'Sharma', 88, 92, 90,97, 89,"no gmail",11),
(3, 'Amit', 'Patel', 92, 89, 90, 89,88,"",11),
(4, 'Anjali', 'Desai', 84, 86, 87,77, 89,"",11),
(5, 'Suresh', 'Mehta', 90, 88, 91,89, 90,"[email protected]",11),
(6, 'Pooja', 'Joshi', 86, 85, 89,78, 87,"",12),
(7, 'Rajesh', 'Gupta', 91, 87, 90, 76,92,"",11),
(8, 'Neeta', 'Singh', 89, 90, 88,90, 91,"",11),
(9, 'Vikas', 'Shah', 87, 91, 89,90, 90,"",11),
(10, 'Mala', 'Verma', 90, 89, 92, 99,88,"",12);

#DISPLAY THE student table


SELECT * FROM student;
OUTPUT

Implement the following SQL commands on the student table:


1. ALTER table to add new attributes / modify data type / drop
attribute
1
13
#ALTER THE TABLE
ALTER TABLE student
ADD COLUMN AGE INT;

ALTER TABLE student


DROP COLUMN EMAIL;

ALTER TABLE student


MODIFY COLUMN first_name VARCHAR(25);

OUTPUT

2. UPDATE table to modify data


UPDATE student
SET age=17

WHERE ROLLNO =2 or ROLLNO=3;


UPDATE student
SET age =16
WHERE ROLLNO = 1;
UPDATE student
SET name= "NITA"
WHERE ROLLNO = 8;

1
14
OUTPUT

3. ORDER By to display data in ascending / descending order


SELECT * FROM student
ORDER BY CHEMISTRY ASC

OUTPUT

SELECT * FROM student


ORDER BY PHYSICS DESC;

1
15
4. DELETE to remove tuple(s)
DELETE FROM student
WHERE ROLLNO=6;

OUTPUT

5. GROUP BY and find the min, max, sum, count and average

SELECT CLASS ,COUNT(*) FROM STUDENT


GROUP BY CLASS;

OUTPUT

SELECT
MIN(age) AS min_age,
MAX(age) AS max_age,
COUNT(*) AS total_students,
AVG(PHYSICS) AS avg_in_physics,
AVG(CHEMISTRY) AS avg_in_chemistry,
AVG (MATHS) AS avg_in_maths,
AVG(COMPUTER_SCIENCE) AS avg_in_cs,
AVG(BIOLOGY) AS avg_in_bio
FROM student;

21
PROGRAM 11
Integrate SQL with Python by importing suitable module.
import mysql.connector
conn=mysql.connector.connect(host="localhost",username="root",password="",database="stu_info",a
uth_plugin="mysql_native_password")
cursor=conn.cursor()
if conn.is_connected():
print("Connection Established Success")
else:
print("Connection Failed ")
cursor.execute("SELECT * FROM stu_info.student")

for i in cursor:
print(i)

OUTPUT

22
Take a sample of ten phishing e-mails (or any text file) and find most
commonly occurring word(s).

23

You might also like