CS Practical 3F (3)
CS Practical 3F (3)
COMPUTER
SCIENCE (083)
PROGRAMMING FILE
SUBMITTED BY : MOHAK CHUGH
SUBMITTED TO:
CLASS : XII-A
ROLL NO. :
INDEX
2 SQL
4 STACKS
5 CONNECTIVITY
Q1. WAP to enter 2 numbers from user and perform addition and subtraction
operations on them.
OUTPUT:
Q2.WAP to enter length and breadth from user and print area and perimeter
depending upon user’s choice.
OUTPUT:
Q3. WAP to enter 2 numbers from user and swap them using the third
variable.
OUTPUT:
Q4. WAP to enter 2 numbers from user and an operator and print the result
depending upon operator’s choice
OUTPUT:
import math
print('enter values for (ax^2 + bx + c = 0) (a is not 0)')
a=int(input('a='))
if a==0:
print('wrong, please enter a non-zero value')
else:
b=int(input('b='))
c=int(input('c='))
D=(b*b)-(4*a*c)
if D<0:
print('No real roots exist')
else:
r1=(-b+math.sqrt(D))/(2*a)
r2=(-b-math.sqrt(D))/(2*a)
print('The roots are',r1,'and',r2)
OUTPUT:
OUTPUT:
Q7. WAP to enter a no and a string and replicate the string that number of
times.
string=input('enter text ')
n=int(input('enter no. of replications'))
print((string+' ')*n)
OUTPUT:
Q8. WAP to display Fibonacci series until the number entered by user.
OUTPUT:
OUTPUT:
Q10. WAP to enter a no. from user and print if it is prime or not.
OUTPUT:
Q11. WAP that inputs a line of text and prints out the count of vowels in it
a=input('enter string: ')
s=0
for i in 'aeiou':
s+=a.count(i)
print('no. of vowels =',s)
OUTPUT:
Q12. WAP that displays options for inserting or deleting elements in a list. If
the user chooses a deletion option, display a submenu and ask if element to be
deleted with value or by using its position or a list slice is to be deleted.
val=[17,23,18,19]
print('the list is:',val)
while True:
print('''Main Menu
1. Insert
2. Delete
3. Exit''')
ch=int(input('enter choice (s.no.): '))
if ch==1:
item=int(input('enter item: '))
pos=int(input('insert at which position?: '))
val.insert(pos-1,item)
print('Done! List is now',val)
elif ch==2:
print('''Deletion Menu
1. Delete using value
2. Delete using index
3. Delete a sublist''')
dch=int(input('enter choice (s.no.)'))
if dch==1:
item=int(input('enter item to be deleted: '))
val.remove(item)
print('the list is now',val)
elif dch==2:
index=int(input('enter index of item to be deleted'))
val.pop(index)
print('the list is now',val)
elif dch==3:
l=int(input('Enter lower limit of sublist to delete'))
h=int(input('Enter upper limit of sublist to delete'))
del val[l-1:h]
print('list is now: ',val)
else:
print('please choose from 1/2/3')
elif ch==3:
break
else:
print('please choose from 1/2/3')
OUTPUT:
Q13. WAP to input a 4-element tuple and unpack it to 4 variables. Then
recreate the tuple with elements swapped as 1st element with 3rd element and
the 2nd element with 4th element.
OUTPUT:
Q14. WAP to add new students’ roll numbers and marks in dictionary M
created with roll numbers as the keys and marks as the values.
M={}
n=int(input('how many students? '))
for i in range(n):
r,m=eval(input('enter roll no., Marks: '))
M[r]=m
print('created dictionary')
print(M)
while True:
print('enter details of new student')
r,m=eval(input('Roll no., Marks: '))
M[r]=m
ch=input('enter more students? (y/n): ')
if ch=='n':
break
print('Dictionary after adding new students:')
print(M)
OUTPUT:
import json
sentence='This is a super idea This idea will change the idea of learning'
words=sentence.split()
d={}
for i in words:
if i not in d:
ctr=words.count(i)
d[i]=ctr
print('Counting frequencies in list \n',words)
print(json.dumps(d,indent=1))
OUTPUT:
Q16. WAP to create a dictionary with the roll number, name and marks of n
students in a class and display the names of those students who have marks
above 75
OUTPUT:
Q17. WAP to read a sentence and then create a dictionary contains the
frequency of letters and digits in the sentence. Ignore other symbols, if any.
OUTPUT:
Q18. A dictionary contains details of 2 workers with their names as keys and
other details in the form of dictionary as value. WAP to print the workers
information in records format.
Employees={'John':{'age':25,'salary':20000},'Diya':{'age':35,'salary':50000}}
for i in Employees:
print('Employee',i,':')
print('Age:',str(Employees[i]['age']))
print('Salary:',str(Employees[i]['salary']))
OUTPUT:
Q19. WAP to input a string and check if it is a palindrome string using a
string slice.
OUTPUT:
Q20. WAP to input n numbers from the user. Store these numbers in a tuple.
Print the maximum and minimum number from this tuple.
OUTPUT:
Q21. WAP that inputs 2 tuples and creates a third, that contains all elements
of the first followed by all elements of second.
OUTPUT:
SQL
OUTPUT:
[2] Insert into employee
OUTPUT:
[3] Delete from employee
OUTPUT:
[4] Fetching record with criteria:
OUTPUT:
[5] Maximum, Minimum, Sum and Average of Salary
mysql> select min(salary) min, max(salary) max, sum(salary) sum, avg(salary) avg from
employee;
OUTPUT:
[6] Group By
OUTPUT:
[7] Sorting in Descending Order
OUTPUT:
[8] Alter Table
OUTPUT:
DATA FILE HANDLING
TEXT FILE
Q1. Read a text file “student.txt” and display with the help of a function:
No. of vowels
No. of consonants
No. of uppercase characters
No. of lowercase characters
f=open('student.txt')
def counter(f):
v=c=uc=lc=0
r=f.read()
for i in r:
if i in 'aeiou':
v+=1
if i.isalpha() and i not in 'aeiou':
c+=1
if i.isupper():
uc+=1
if i.islower():
lc+=1
return(v,c,uc,lc)
v,c,uc,lc=counter(f)
print('no. of vowels=',v)
print('no. of consonants=',c)
print('no. of uppercase characters=',uc)
print('no. of lowercase characters=',lc)
OUTPUT:
Q2. Read all data from a text file and print all lines not containing ‘a’.
f=open('student.txt')
l=f.readlines()
for i in l:
if 'a' not in i:
print(i)
f.close()
OUTPUT:
Q3. Input a list of strings from user and write all lines in ‘modify.txt’
containing a special character.
OUTPUT:
Q4. WAP to transfer lines from ‘student.txt’ starting with P and ending with
T into ‘modify.txt’ (irrespective of case)
fr=open('student.txt')
f=open('modify.txt','w')
l=fr.readlines()
fr.close()
for i in l:
if i.upper()[0]=='P' and i.upper()[-2]=='T':
f.write(i+'\n')
f.close()
OUTPUT:
BINARY
Q1. Write a function disp() to display all records from the file.
import pickle
def disp():
try:
f=open("data.dat","rb")
while True:
d=pickle.load(f)
print(d)
except:
f.close()
disp()
OUTPUT:
Q2. Consider a binary file containing a list. Only print those elements where
the element and index both are even.
import pickle
f=open('data.dat','rb')
l=pickle.load(f)
for i in range(0,len(l),2):
if l[i]%2==0:
print(l[i])
OUTPUT:
Q3. Write a function addrec() to add a record in a file.
import pickle
def addrec():
L=[]
f=open("data.dat","ab")
rn=int(input("Enter room number"))
pr=int(input("Enter the price of room"))
rt=input("Enter the type of room")
L=[rn,pr,rt]
pickle.dump(L,f)
print("Record added in the file")
f.close()
addrec()
CSV
import csv
f=open("data.csv","w")
f1=open("temp.csv","w")
d=csv.reader(f)
d1=csv.writer(f1)
for i in d:
d1.writerow(i)
f.close()
f1.close()
Q2. A CSV file ‘student.csv’ has data stored as (roll_no, name, marks). Print
the details of student with maximum and minimum marks.
import csv
f=open('student.csv')
l=csv.reader(f)
l1=[]
max=l[0]
min=l[0]
for i in l:
if i[2]>max[2]:
max=i
if i[2]<min[2]:
min=i
print('top scorer:',max)
print('bottom scorer:',min)
STACKS
st=[]
def push(stk,e):
stk.append(e)
print(stk[::-1])
for i in range(n):
push(st,el)
OUTPUT:
Q2. Write a function to display the stack elements.
def display(stk):
if stk==[]:
print("Stack is Empty")
else:
for i in stk:
print(i)
st=[1,2,3,4,5,6]
display(st)
OUTPUT:
Q3. Write a function to print the last element of the stack.
def peek(stk):
if stk==[]:
return "UnderFlow"
else:
top = len(stk)-1
print(stk[top])
sl=list(s)
peek(sl)
OUTPUT:
Q4. Write a function to print and remove the last element of the stack.
def pop(stk):
if stk==[]:
print('underflow')
else:
e=stk.pop()
print(e,'has been deleted')
stk=eval(input('enter stack'))
pop(stk)
OUTPUT:
Q5. Write a program to implement a stack to store phone numbers and names
of n employees with the following operations: deleteany(name) (to remove the
employee with given name) and insertat(n,rec) (to insert record rec at index
n).
def deleteany(name):
flag=0
for i in stk:
if i[1]==name:
stk.remove(i)
flag=1
break
if flag==0:
print('nobody of name',name,'present in stack')
else:
print('data of',name,'has been removed')
def insertat(n,rec):
if n>=len(stk):
print('index out of range...')
else:
stk.insert(n,rec)
print(rec,'has been added')
stk=eval(input('enter stack of record: '))
while True:
ch=int(input('''choose:
1. delete a record
2. insert a record
3. exit
enter s.no.: '''))
if ch==1:
name=input('enter name to remove: ')
deleteany(name)
elif ch==2:
n=int(input('enter index: '))
rec=eval(input('enter record: '))
insertat(n,rec)
elif ch==3:
break
else:
print('please enter valid s.no.')
OUTPUT:
CONNECTIVITY
import mysql.connector
db =
mysql.connector.connect(host="localhost",user="root",passwd="0w01234!",database='project')
cur1 = db.cursor()
Empl_id=int(input('enter employee id: '))
Name=input('enter name of employee: ')
dep=input('enter department of employee: ')
gen=input('enter gender (M/F): ')
sal=int(input('enter salary of employee: '))
cur1.execute("insert into staff values({},'{}','{}','{}',{})".format(Empl_id,Name,dep,gen,sal))
db.commit()
cur1.close()
OUTPUT:
Q2. Fetch records from employee where salary is less than the value entered
by user.
import mysql.connector
db =
mysql.connector.connect(host="localhost",user="root",passwd="0w01234!",database='project')
cur1 = db.cursor()
n=int(input('enter minimum salary: '))
cur1.execute('select*from employee where salary<{}'.format(n))
r=cur1.fetchall()
for i in r:
print(i)
OUTPUT: