0% found this document useful (0 votes)
25 views45 pages

CS Practical 3F

Uploaded by

Jaskirat Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views45 pages

CS Practical 3F

Uploaded by

Jaskirat Kaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

SESSION 2022-23

COMPUTER
SCIENCE (083)
PROGRAMMING FILE
SUBMITTED BY : MOHAK CHUGH
SUBMITTED TO:
CLASS : XII-A
ROLL NO. :
INDEX

S.NO. TOPIC DATE TEACHER’S


SIGNATURE
1 PYTHON

2 SQL

3 DATA FILE HANDLING

4 STACKS

5 CONNECTIVITY
Q1. WAP to enter 2 numbers from user and perform addition and subtraction
operations on them.

a=int(input('enter first no.'))


b=int(input('enter second no.'))
print('sum is',a+b)
print('difference is',a-b)

OUTPUT:

Q2.WAP to enter length and breadth from user and print area and perimeter
depending upon user’s choice.

l=int(input('enter length of rectangle:'))


b=int(input('enter breadth of rectangle:'))
ch=input('''choose required value (enter s.no.):
1.Perimeter
2.Area''')
if ch=='1':
print('Perimeter is',2*(l+b))
elif ch=='2':
print('Area is',l*b)
else:
print('invali choice')

OUTPUT:
Q3. WAP to enter 2 numbers from user and swap them using the third
variable.

a=int(input('enter first no.:'))


b=int(input('enter second no.:'))
temp=a
a=b
b=temp
print('First no. is ',a)
print('Second no. is',b)

OUTPUT:

Q4. WAP to enter 2 numbers from user and an operator and print the result
depending upon operator’s choice

a=int(input('enter first no:'))


b=int(input('enter second no:'))
op=input('enter operator(+,-,*,/):')
if op=='+':
print('sum is',a+b)
elif op=='-':
print('difference is',a-b)
elif op=='*':
print('product is',a*b)
elif op=='/':
print('quotient(in decimal) is',a/b)
else:
print('invalid option')

OUTPUT:

Q5. WAP to find the roots of a quadratic equation.

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:

Q6. WAP to enter a number from user and check if it is an Armstrong


number.
n=int(input('enter no.:'))
num=n
sum=0
if n<=0:
print('please enter a value greater than 0')
else:
while n>0:
d=n%10
n=n//10
sum=sum+(d**3)
if s==num:
print('it is an armstrong no.')
else:
print('it is not an armstrong no.')

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.

n=int(input('enter last no. of series'))


a=0
b=1
c=a+b
while c<=n:
print(c,end=' ')
a=b
b=c
c=a+b

OUTPUT:

Q9. WAP to print the following pattern:


*
**
***
****
n=int(input('enter no. of lines '))
for i in range(1,n+1):
print('*'*i)

OUTPUT:

Q10. WAP to enter a no. from user and print if it is prime or not.

n=int(input('enter no: '))


x=1
for i in range(2,n//2):
x=n%i
if x==0:
break
if x==0:
print('it is not prime')
else:
print('it is prime')

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.

tup=eval(input('enter a 4 element tuple'))


a,b,c,d=tup
print('tuple unpacked in',a,b,c,d)
tup=c,d,a,b
print('tuple after swapping elements:',tup)

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:

Q15. WAP to count the frequency of a list of elements using a dictionary.

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

n=int(input('how many students?: '))


stu={}
for i in range(1,n+1):
print('enter details of student',i)
rollno=int(input('Roll number: '))
name=input('Name: ')
marks=float(input('marks: '))
d={'Roll_no':rollno,'Name':name,'Marks':marks}
key='stu'+str(i)
stu[key]=d
print('Students with marks >75 are: ')
for i in range(1,n+1):
key='stu'+str(i)
if stu[key]['Marks'] >=75:
print(stu[key])

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.

sen=input('enter a sentence: ')


sen=sen.lower()
char_count={}
print('Total characters in the sentence are:',len(sen))
for i in sen:
if i in 'qwertyuiopasdfghjklzxcvbnm1234567890':
if i in char_count:
char_count[i]+=1
else:
char_count[i]=1
print(char_count)

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.

s=input('enter a string: ')


if s==s[::-1]:
print(s,'is a palindrome')
else:
print(s,'is not a palindrome')

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.

n=int(input('how many no.s?: '))


l=[]
for i in range(1,n+1):
print('enter no.',i,':',end=' ')
num=int(input())
l.append(num)
tup=tuple(l)
print('tuple formed: ',tup)
print('maximum value:',max(tup))
print('minimum value:',min(tup))

OUTPUT:
Q21. WAP that inputs 2 tuples and creates a third, that contains all elements
of the first followed by all elements of second.

tup1=eval(input('enter first tuple: '))


tup2=eval(input('enter second tuple: '))
print('third tuple:',tup1+tup2)

OUTPUT:
SQL

[1] Create table employee

create table employee


-> (Empl_id int primary key,
-> Name varchar(30) not null,
-> department varchar(30),
-> gender char(1),
-> salary int not null);

OUTPUT:
[2] Insert into employee

mysql> insert into employee values


-> (1243, 'Max', 'Management', 'M', 230000),
-> (2345, 'Joe', 'Sales', 'M', 400000),
-> (3245, 'Skyler', 'Transport', 'F', 110000);

OUTPUT:
[3] Delete from employee

mysql> delete from employee where Empl_id=3245;

OUTPUT:
[4] Fetching record with criteria:

mysql> select*from employee where salary>30000;

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

mysql> select department, count(*) num from employee


-> group by department;

OUTPUT:
[7] Sorting in Descending Order

mysql> select*from employee


-> order by salary desc;

OUTPUT:
[8] Alter Table

mysql> alter table employee


-> add age int;

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.

l=eval(input('enter list: '))


f=open('modify.txt','w')
for i in l:
for j in i.split():
if j.isalnum():
pass
else:
f.write(i+'\n')
continue
f.close()

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

Q1. Write a program to copy the data from “data.csv” to “temp.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

Q1. Write a function to push an element into the stack.

st=[]

def push(stk,e):

stk.append(e)

print(stk[::-1])

n=int(input("How many elements do you want?:"))

for i in range(n):

el=eval(input("Enter stack elements:"))

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

s=eval(input("Enter stack elements:"))

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

Q1. WAP to insert a new employee in table ‘employee’. Assign Empl_id,


Name, Department, Gender and Salary.

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:

You might also like