3fin
3fin
OUTPUT
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
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
OUTPUT
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:
create_prof()
elif choice == 2:
search()
else:
print("Invalid choice. Please enter a valid option.")
break
OUTPUT
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.
stack = [1, 2, 3, 4]
def is_empty():
return len(stack) == 0
def push():
value = input("Enter element: ")
stack.append(value)
def pop():
if is_empty():
print("Empty Stack")
else:
print("Popped:", stack.pop())
def peek():
if is_empty():
print("Empty Stack")
else:
print("Top element:", stack[-1])
def display():
print("Stack:")
for i in range(len(stack) - 1, -1, -1):
print(stack[i])
while True:
print("\nStack Program Menu:")
print("1. Push (Add item to stack)")
print("2. Pop (Remove item from stack)")
print("3. Peek (View top item)")
print("4. Display Stack")
print("5. Quit")
if choice == "1":
push()
display()
elif choice == "2":
pop()
display()
elif choice == "3":
peek()
elif choice == "4":
display()
elif choice == "5":
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
OUTPUT
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")
INPUT
OUTPUT
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
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
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
PROGRAM 13
Write user defined functions to read and write operations onto a
'student.csv' file having fields: roll number, name, stream and marks.
import csv
def stdcsv():
info = []
n = int(input("Enter number of students: "))
for i in range(n):
li = []
roll = input("Enter roll number: ")
name = input("Enter name: ")
stream = input("Enter stream: ").lower()
marks = input("Enter marks: ")
li.extend((roll,name,stream,marks))
info.append(li)
with open("student.csv", "a", newline="") as data:
write = csv.writer(data)
write.writerow(["Roll", "Name", "Stream","Marks"])
write.writerows(info)
def readcsv():
with open("student.csv", "r", newline="") as data:
reader = csv.reader(data)
for i in reader:
print(i)
if choice == 1:
stdcsv()
elif choice == 2:
readcsv()
else:
print("Invalid Choice")
break
OUTPUT
PROGRAM 14
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")
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: ")
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()
OUTPUT
LIST OPERATIONS
TUPLE OPERATIONS
DICTIONARY OPERATIONS
PROGRAM 15
Write a program that performs conversions of a list, a tuple and a
dictionary into each other.
my_list = [1, 2, 3]
my_tuple = ('a', 'b', 'c')
my_dict = {1: 'one', 2: 'two', 3: 'three'}
# List to Tuple
list_to_tuple = tuple(my_list)
# Tuple to List
tuple_to_list = list(my_tuple)
OUTPUT
PROGRAM 16
Create a student table and insert data
CREATE TABLE IF NOT EXISTS student (
ROLLNO INT PRIMARY KEY ,
FIRST_NAME VARCHAR(50),
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);
OUTPUT
OUTPUT
3. ORDER By to display data in ascending / descending order
SELECT * FROM student
ORDER BY CHEMISTRY ASC
OUTPUT
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
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;
PROGRAM 17
Create a table 'employee' and insert data
CREATE TABLE IF NOT EXISTS Employee (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(100),
Salary INT
);
SELECT * FROM Employee;
OUTPUT
import mysql.connector
conn=mysql.connector.connect(host="localhost",username="root",password="",database="stu_info",
auth_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.employee")
OUTPUT
#Sports table
select s.first_name,s.surname,sp.name,sp.team_name,sp.teacher
from sports sp
inner join student s
on s.sports = sp.name;
OUTPUT
PROGRAM 19
Integrate SQL with Python by importing suitable module.
import mysql.connector
conn=mysql.connector.connect(host="localhost",username="root",password="",database="stu_info",
auth_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