Cs Practicals
Cs Practicals
Cs Practicals
function and double the odd values and half even values of a list and display
elements of list after changing.
def splitevenodd(A):
evenlist=[]
oddlist=[]
for i in A:
if(i%2==0):
evenlist.append(i//2)
else:
oddlist.append(i*i)
print("Even List:",evenlist)
print("Odd List:",oddlist)
A=list()
n=int(input("Enter the size of the List::"))
print("Enter the Elements of LIst::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
splitevenodd()
Output:
Assignment 2: Write a Python program input n numbers in tuple and count
how many even and odd numbers are entered.
l=[]
S=int(input("Please Enter the Total Number of
Elements :"))
for i in range(S):
value = int(input("Please enter the %d Element of
list1:"%i))
l.append(value)
numbers=tuple(l)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Numbers of even numbers:",count_even)
print("Numbers of odd numbers:",count_odd)
Output:
#Assignment3: Write a menu driven program in python to delete the name of a
student from the dictionary and to search the phone no of a student-by-student
name. Create menu as below:
******MENU******
1.Delete from dictionary
2.Search Phone number using name from Dictionary
3.Exit
phonebook = dict()
while True:
print("******MENU******\n")
print("1: Delete from Dictionary")
print("2: Search Phone number using name from Dictionary")
print("3: Exit\n")
ch = int(input("Enter your choice: "))
if ch == 1:
n = int(input("Enter total number of friends: "))
i = 1
while i <= n:
a = input("Enter name: ")
b = int(input("Enter phone number: "))
phonebook[a] = b
i += 1
print(phonebook)
print("-------------------------------")
Output:
#Assignment 4: Write a menu driven program to do following
MENU
1: Reverse String
2: Check whether string is palindrome
3: Make half string in Uppercase
4: Exit
Output:
#Assignment 5: Write a program to read a list of n integers (positive as well
as negative). Create two new lists, one having all positive numbers with sum
and the other having all negative numbers with sum from the given list.
list1=[ ]
plist1=[ ]
nlist1=[ ]
sum=0
sum1=0
n=int(input("how many elements u want in list:"))
for i in range(0,n):
a=int(input("enter item in list:"))
list1.append(a)
print("original list is :",list1)
for i in range(0,n):
if list[i]<0:
nlist1.append(list1[i])
sum=sum+list1[i]
else:
list1.append(list1[i])
sim1=sum1+list1[i]
print("positive list is;',plist1)
print("sum pf +ve numbers:',sum1)
print("negative list is;',nlist1)
print("sum of -ve numbers:',sum)
Output:
#Assignment 6: Write a Python program to remove duplicates from a list.
a = []
n = int(input("how many elements do you want in list: "))
for i in range(0, n):
n1 = int(input("enter item in list"))
a.append(n1)
print("original list is: ", a)
print("list after removing duplicate elements: ")
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Output:
#Assignment 7: Write a menu driven program to generate random numbers
given in a specific range and to display calendar after giving month and year.
import random
import calendar
while True:
print("********MENU********\n")
print("1:Random number generators")
print("2:Calender of a month")
print("3:Exit\n")
ch = int(input("enter your choice:"))
if ch == 1:
num = 10
start = 20
end = 40
res = []
for j in range(num):
res.append(random.randint(start, end))
print(res)
if ch == 2:
yy = int(input("enter year:"))
mm = int(input("enter month:"))
print(calendar.month(yy, mm))
if ch == 3:
break
Output:
#Assignment 8:
Write a python program to read and displays file content line by line with each
word separated by #.
Output:
#Assignment 9: Write a python program Read a text file and display the
number of vowels/consonants/uppercase/lowercase alphabets in the file.
Output:
#Assignment 10: Write a python code that accepts a filename and copies all
lines that do not start with a lowercase letter from the first file into the second.
fin.close()
fout.close()
Output:
#Assignment 11: Write a python program to remove all the lines that contain
the character ‘a’ in a file and write it to another file.
file = open("file.txt", "w")
file.write("Harry Potter")
file.write(
"There is a difference in all harry potter books \n We can
see it as harry grows \n the books were written by J.K
Rowling"
)
file.close()
file = open("file.txt", "r")
docx = open("docx.txt", "w")
len = docx.readlines()
for i in len:
if "a" in i:
i = i.replace("a", "")
file.write(i)
file.close()
docx.close()
Output:
#Assignment 12: Write a python program to create a binary file with name and roll
number. search for a given roll number and display name, if not found display
appropriate message.
Output:
Enter roll number: 24
Enter Name: Himanshu Deep
Wish to enter more record(Y/N): Y
Enter roll number:15
Enter Name: Satyam
Wish to enter more record(Y/N): N
Enter roll no. to be searched:24
Name Himanshu Deep
#Assignment 13: Write a python program to create a binary file with roll
number, name and marks. Input a roll number and update name and marks.
import pickle
while True:
f = open("student1.dat", "ab")
pickle.dump(rec, f)
if ch == "N" or ch == "n":
break
f.close()
f = open("student1.dat", "rb+")
found = 0
try:
while True:
rec = pickle.load(f)
if rec["Rollno"] == r:
found = 1
break
except EOFError:
print("End of file")
if found == 1:
f.seek(0)
pickle.dump(rec, f)
print("Record updated")
f.close()
Output:
Assignment 14: Write a menu driven python program to create a CSV
file by entering dept-id, name and city, read and search the record for
given dept-id.
MENU
1. Create csv
2. Search
3.Exit
import csv
while True:
print("***MENU***\n")
print("1: create csv file")
print("2: Search as per id")
print("3: Exit")
ch = int(input("Enter choice: "))
if ch == 1:
f = open("dept.csv", "a")
mywriter = csv.writer(f, delimiter=",")
ans = "y"
while ans.lower() == "y":
rno = int(input("Enter dept no.: "))
name = input("Enter dept name: ")
clas = input("Enter city: ")
mywriter.writerow([rno, name, clas])
print("## Data Saved ##")
ans = input("Add More?: ")
f.close()
if ch == 2:
print("Search a Record")
print("=========================")
f = open(
"dept.csv", "r", newline="\r\n"
) # Remove new line character from output
r = input("Enter DEPT no. you want to searc: ")
s = csv.reader(f)
for rec in s:
if rec[0] == r:
print("Dept no.=", rec[0])
print("Dept name=", rec[1])
print("city", rec[2])
f.close()
if ch == 3:
break
Output:
Assignment 15: .Write a Menu
driven program in python to count spaces, digits, words and lines from
text file try.txt
while True:
print("***MENU***\n")
print("1: count spaces")
print("2: count digits")
print("3: count words")
print("4: count lines")
print("5: exit")
ch = int(input("Enter your choice: "))
if ch == 1:
F1 = open("abc.txt", "r")
c = 0
F = F1.read()
for letter in F:
if letter.isspace():
c = c + 1
print("No. of spaces are: ", c)
F1.close()
if ch == 2:
F1 = open("abc.txt", "r")
c = 0
F = F1.read()
for letter in F:
if letter.isdigit():
c = c + 1
print("No. of digits are: ", c)
F1.close()
if ch == 3:
F1 = open("abc.txt", "r")
linesList = F1.readlines()
c = 0
for line in linesList:
wordsList = line.split()
print(wordsList)
c += len(wordsList)
print("The Number of words in this file are: ",
c)
F1.close()
if ch == 4:
c = 0
F1 = open("abc.txt", "r")
data = F1.readlines()
print(data)
for line in data:
c += 1
print("Number of lines: ", c)
F1.close()
if ch == 5:
break
Assignment 16: Write a python program using the function PUSH (Arr),
where Arr is a list of numbers. From this list push all numbers divisible by
5 into a stack implemented by using a list. Display the stack if it has at
least one element, otherwise display appropriate error messages.
def isEmpty(Arr):
if len(Arr) == 0:
return True
else:
return False
def push(Arr, item):
if item % 5 == 0:
Arr.append(item)
top = len(Arr) - 1
def show(Arr):
if isEmpty(Arr):
print("No item found")
else:
t = len(Arr) - 1
print("(TOP)", end="")
while t >= 0:
print(Arr[t], "<==", end="")
t = t - 1
print()
Arr = []
top = None
while True:
print("******STACK IMPLEMENTATION USING LIST******")
print("1:PUSH")
print("2:Show")
print("0:Exist")
ch = int(input("Enter choice:"))
if ch == 1:
val = int(input("Enter no to push:"))
push(Arr, val)
elif ch == 2:
show(Arr)
elif ch == 0:
print("Bye")
break
Output:
Assignment 17: Write a python program using function POP(Arr),
where Arr is a stack implemented by a list of numbers. The function
returns the value deleted from the stack.
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
Arr.append(item)
top=len(Arr)-1
def pop(Arr):
if isEmpty(Arr):
return 'Underflow'
else:
val = Arr.pop()
if len(Arr)==0:
top = None
else:
top=len(Arr)-1
return val
def show(Arr):
if isEmpty(Arr):
print('no item found')
else:
t = len(Arr)-1
print('(TOP)',end="")
while t>=0:
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top = None
while True:
print("******** STACK IMPLEMENTATION USING
LIST********")
print('1:PUSH')
print('2:POP')
print('3:SHOW')
print('0:EXIT')
ch=int(input("Enter choice: "))
if ch==1:
val=int(input("Enter no to push: "))
push(Arr,val)
elif ch==2:
val=pop(Arr)
if val=='Underflow':
print('Stack is empty: ')
else:
print("\nDeleted item is: ",val)
elif ch==3:
show(Arr)
elif ch==0:
print('Bye')
break
Output:
Assignment 18:
Consider the table FLIGHT given below. Write commands in SQL for
Table: PRODUCTS
FLCOD START DESTINATIO NO_STOPS NO_FLIGHTS
E N
IC101 DELHI AGARTALA 1 5
IC102 MUMBAI SIKKIM 1 3
IC103 DELHI JAIPUR 0 7
IC105 KANPUR CHENNAI 2 2
IC107 MUMBAI KANPUR 0 4
IC431 INDORE CHENNAI 3 2
IC121 DELHI AHEMDABAD 2 6
TABLE: FARES
Table: SUPPLIERS
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA
S03 EASY MARKET CORP DELHI
S02 DIGI BUSY GROUP CHENNAI
● To arrange and display all the records of table products on the basis of product name
in the ascending order.
● To display product name and price of all those products whose price is in the range
of 10000 and 15000(both values inclusive)
● TO display the price, products name and quantity (i.e,qty) of those products which
are having quantity more than 100.
● To display the names of those suppliers who are either from DELHI or from
CHENNAI.
● TO display the maximum and minimum price of products.
ANSWERS:
Table: EMPSALARY
EMPID SALARY BENIFITS DESIGNATION
010 75000 15000 Manager
105 65000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
400 32000 7500 Salesman
441 28000 7500 Salesman
1. To display Firstname, Lastname, Address and City of the employees living in Paris
from the table EMPLOYEES.
2. To display the content of EMPLOYEES table in descending order of FIRSTNAME.
3. To display the Firstname, Lastname and Total Salary of all the managers from the
table where total salary is calculated as salary + Benefits.
4. To display the maximum salary among Managers and Clerks from table EMPSALARY
5. To display all records from both the table by using natural join
ANSWER:
1. SELECT FIRSTNAME, LASTNAME, ADDRESS, CITY FROM EMPLOYEES
WHERE CITY=”PARIS”;
HOUSE
HI LOCATION QUANTIT UNIT_PRIC DCOD
D Y E E
H Raipur 10 500000 1
1
H Bilaspur 20 300000 2
2
H Bargarh 15 200000 3
3
H Ambikapu 25 250000 2
4 r
H Raipur 25 280000 2
5
H Bilaspur 20 240000 1
6
import os
import platform
import mysql.connector
mydb=mydb.connector.connect(host='localhost',
user='root', passwd='123',database='student')
print(mydb
mycursor=mydb.cursor()
def stulnert():
L=[]
roll=int(input('ENTER THE ROLL NUMBER:'))
L.append(roll)
name-input('ENTER THE NAME:')
L.append(name)
age=int(input('ENTER THE AGE OF STUDENT:'))
L.appent(age)
clas=input('ENTER THE CLASS:')
L.append(clas)
stud=(L)
sql='insert into stud(roll,name,age,clas) values
(%s,%s,%s,%S)'
mycursor.execute(sql,stud)
mydb.commit()
def stuview():
mycursor.excute('select * from stud')
myrus=mycursor.fetchall()
for x in myrus:
print(x)
def runAgain():
runagn=input('\n Want to run again Y/N:')
while(runagn.lower()=="y"):
if (platform.system()=="Windows")
print(os.system('clas'))
else:
print(os.system("clear"))
MenuSet()
def runAgain():
runagn=input('\n Want to run again Y/N:')
while(runagn.lower()=="y"):
if (platform.system()=="Windows")
print(os.system('clas'))
else:
print(os.system("clear"))
MenuSet()
runagn=input('\n Wnat to run again Y/N:')
runagn()
Assignment 24: Integrate MySQL with Python by importing the MySQL
module to search using roll no, name, age, class and if present in table
display the record, if not display appropriate method.
import mysql.connector
import os
import platform
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="123",
database="student"
)
cursor = mydb.cursor()
def stuview():
print("Select the search criteria: ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Class")
print("5. All")
ch = int(input("Enter the choice: "))
if ch == 1:
s = int(input("Enter the roll no: "))
cursor.execute(f"select * from stud where
roll={s}")
elif ch == 2:
s = input("Enter Name: ")
cursor.execute(f'select * from stud where
name="{s}"')
elif ch == 3:
s = int(input("Enter Age: "))
cursor.execute(f"select * from stud where age={s}")
elif ch == 4:
s = int(input("Enter the class"))
cursor.execute(f"select * from stud where class =
{s}")
elif ch == 5:
cursor.execute("select * from stud")
res = cursor.fetchall()
print("The Students details are as follows: ")
print("(Roll,Name,Age,Class)")
for x in res:
print(x)
def menuSet():
print("Enter 1: To Search Student")
userInput = int(input("Please Select an above
option: "))
if userInput == 1:
stuview()
runAgain()
def runAgain():
runAgn = input("\nWant to run agin y/n: ")
if runAgn.lower() == "y":
print(platform.system())
if platform.system() == "Windows":
print(os.system("cls"))
menuSet()
else:
print(os.system("clear"))
menuSet()
menuSet()
Assignment 25: Integrate SQL with Python by importing the MySQL module to
search a student using roll no, delete the record.
import mysql.connector
import os
import platform
print(os.system("apple"))
mydb = mysql.connector.connect(
host="localhost", user="root", passwd="password",
database="mayank"
)
cursor = mydb.cursor()
def removeStu():
roll = int(input("Enter the roll no to ev deleted: "))
cursor.execute(f"delete from stud where roll={roll}")
print("RECORD DELETED!!!")
mydb.commit()
def stuview():
print("Select the search criteria: ")
print("1. Roll")
print("2. Name")
print("3. Age")
print("4. Class")
print("5. All")
ch = int(input("Enter the choice: "))
if ch == 1:
s = int(input("Enter the roll no: "))
cursor.execute(f"select * from stud where roll={s}")
elif ch == 2:
s = input("Enter Name: ")
cursor.execute(f'select * from stud where name="{s}"')
elif ch == 3:
s = int(input("Enter Age: "))
cursor.execute(f"select * form stud where age={s}")
elif ch == 4:
s = int(input("Enter the class"))
cursor.execute(f"select * from stud where class =
{s}")
elif ch == 5:
cursor.execute("select * from stud")
res = cursor.fetchall()
print("The Students details are as follows: ")
print("(Roll,Name,Age,Class)")
for x in res:
print(x)
def menuSet():
print("Enter 1: To Search Student")
print("Enter 2: To Delete Student")
userInput = int(input("Please Select an above option: "))
if userInput == 1:
stuview()
if userInput == 2:
removeStu()
def runAgain():
runAgn = input("\nWant to run agin y/n: ")
if runAgn.lower() == "y":
print(platform.system())
if platform.system() == "Windows":
print(os.system("cls"))
else:
print(os.system("clear"))
menuSet()
runAgn = input("\nWant to run agin y/n: ")
menuSet()
runAgain()
Assignment 26: Integrate SQL with Python by importing the MySQL
module to search a student using roll no, update the record.
import mysql.connector as mycon
cn = mycon.connect(
host="localhost", user="root", passwd="root",
database="student", charset="utf8"
)
cur = cn.cursor()
print("Welcome to studen Details Updation screen...")
print("*********************EDIT STUDENT
DETAILS************************")
ro = int(input("Enter Student's roll number to edit: "))
query = "select * from stud where roll=" + str(ro)
cur.execute(query)
results = cur.fetchall()
if cur.rowcount <= 0:
print("\n## SORRY! NO MATCHING DETAILS AVILABLE ##")
else:
print("********************************************")
print("%5s" % "ROLLNO.", "%15s" % "NAME", "%12s" % "AGE",
"%10s" % "CLASS")
print("********************************************")
for row in results:
print("%5s" % row[0], "%15s" % row[1], "%12s" %
row[2], "%10s" % row[3])
print("-" * 50)
ans = input("Are you sure to update? (y/n): ")
if ans == "y" or "Y":
d = input("Enter new name to update(enter old value if
not to update): ")
s = int(input("Enter new age to update (enter old
value if not to update): "))
query = f"update stud set name={d}, age={str(s)} where
roll={str(ro)}"
cur.execute(query)
cn.commit()
print("\n## RECORD UPDATED ##")