0% found this document useful (0 votes)
36 views12 pages

Practical File For Student Final - 2024-25

Uploaded by

abijeetlimboo2
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)
36 views12 pages

Practical File For Student Final - 2024-25

Uploaded by

abijeetlimboo2
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/ 12

Computer Science with Python

Practical File
1. Python prog. to find all prime numbers upto range given by user using function
def prime_test(n,PrimeNo):
for num in range(1,n+1):
for i in range(2,int(num/2)+1):
if(num%i==0):
break
else:
PrimeNo.append(num)

choice='y'
while(choice=='y' or choice=='y'):
PrimeNo=[]
x=int(input('enter a number upto which, list of prime number you want to create:'))
flag=prime_test(x,PrimeNo)
print('List of Prime Number upto:',x,'is',PrimeNo)
choice=input(' press y to continue n to exit:')
if(choice!='y'):
print('Good by....')

2. Python program to encrypt & decrypt the message string using split() & join() function.
def encrypt(str,key):
return key.join(str)
def decypt(str,key):
return str.split(key)

msg=input('enter a message :')


key1=input('enter encryption key :')
coded_msg=encrypt(msg,key1)
dec=decypt(coded_msg,key1)
actual_msg="".join(dec)
print('The encrypted message is:',coded_msg)
print('String after decryption is :',actual_msg)
3. Write a Python function sin(x, n) to calculate the value of sin(x) using its Taylor series
expansion up to n terms. Compare the values of sin(x) for different values of n with the correct
value.

# sin x = x −x3/3! +x5/5!−x7/7! +x9/9!


import math
ch='y'
while(ch=='y'):
x=float(input('Enter the value of X in degrees'))
radian=math.radians(x)
print('Value of X','in Radians=',radian,'and',' in
Degree=',x) t
erms=int(input('enter the number of terms'))
b=0
for i in range (terms):
a=(((((-1)**i))*(radian**((2*i)+1)))/(math.factorial((2*i)+1)))
b+=a
print('1.value of sin(X) computed according to tayler series in radian',b)
print('2.value of sin(X) correct value as math formula=',math.sin(radian))
print('Now compare the correct value in step 1 with step 2')
ch=input('press y to continue')
4. Python program for random number generator that generates random numbers between 1 and 6
(simulates a dice).

import random
def Number_gen():
counter = 0
myList = [ ]
while (counter) < 6:
randomNumber =
random.randint(1,6)
myList.append(randomNumber)
counter = counter + 1
print(myList)
Number_gen()
5. Python program to count the word 'to' and 'the' in text file 'STORY.txt'

file=open('ABC.txt','r')
c1=c2=0
lines =
file.read()
print(lines)
L=lines.split
() for i in L:
if i=="to":
c1=c1+1
if i=="the":
c2=c2+1
print('No.of \'to\' word in a file',c1)
print('No.of \'the\' word in a file',c2)
file.close()
6. Python program to count the no. of uppercase, lowercase & digit in a text file 'POPULATION.txt'
digit=0
lower=0
upper=0
alpha=0
file=open('poem.t
xt','r')
msg=file.read()
for a in msg:
if a.isupper():
upper+=1
if a.islower():
lower+=1
if a.isdigit():
digit+=1
if a.isalpha():
alpha+=1
print('*'*50)
print('The content of files:\n',msg)
print('*'*50)
print('upper case alphabets in file=',upper)
print('lower case alphabets in file=',lower)
print('digits in file=',digit)
print('alphabets in file=',alpha)

7.Python program to count the no. of lines start with either with 'A' and 'M' and display those lines.

def countAM():
c1=c2=0
file=open('delhi.txt','r')
str=' '
msg=file.readlines()
for k in msg:
if(k[0]=='A' or
k[0]=='a'): c1=c1+1
if(k[0]=='M'or
k[0]=='m'): c2=c2+1
file.close()
return c1,c2
# main start here
print('no of lines start with (A/a) and (M/m) are',countAM())
8. Python program to write the record of 5 students in a text file having roll_no, name &
marksalso read the data from file and display.
file=open("student.txt",'w+')
print('Read the data of 5 students')
for i in range(5):
print('enter data for student',i+1)
roll_no=input('enter the Roll number of student
:') Name=input('enter the Name of student :')
mark=input('enter the Mark of student :')
record=roll_no+","+Name+","+mark+'\n'
file.write(record)
file.seek(0)
for i in range(5):
m=file.readline()
print('Data of student :',i+1)
print(m)
file.close()
9. Python program to read text file "REPORT.txt" and write those lines that start with 'A' into
another file "FINAL.txt"
file1=open('report.txt','r+')
file2=open('final.txt','w+')
str=file1.readlines( )
for line in str:
if (line[0]=='a' or line[0]=='A'):
file2.write(line)
file2.seek(0)
x='’
print('The content of source file \n',str)
print('Now the content of final file')
while x:
x=file2.readline()
print(x)
file1.close()
file2.close()
10. Python prog. to write the student data in binary file.
import pickle
data=[ ]
choice='y'
while( choice=='y' or choice=='Y'):
roll_no=int(input('Enter the Roll Number of
student :')) name=input('Enter the name of
student :') marks=float(input('Enter the marks of
student :')) record=[roll_no,name,marks]
data.append(record)
choice=input('Press y to enter more record :')
file=open(‘student.dat','wb+')
pickle.dump(data,file)
print('Now data of students inserted into file') file.seek(0) # Now move the file pointer
at starting of the file
print('*********A*F*T*E*R*****R*E*A*D*I*N*G********')
print('******F*R*O*M**T*H*E**F*I*L*E**************')
stu_data=pickle.load(file)
for raw in stu_data:
rno=raw[0]
name=raw[1]
mark=raw[2]
print('Roll No- ',rno,' Name- ',name,'Marks-
',mark)
file.close()
11. Python program search a record in binary file according to roll no. python prog.
to create a binary file first write data into this and search for a record by roll no.
import pickle def
writeBinary( ):
data=[ ]
choice='y'
while( choice=='y' or choice=='Y'):
roll_no=int(input('Enter the Roll Number of student :'))
name=input('Enter the name of student :')
marks=float(input('Enter the marks of student :'))
record=[roll_no,name,marks]
data.append(record)
choice=input('Press y to enter more record :')
file=open('stu11.dat','wb')
pickle.dump(data,file)
print('Now data of students inserted into file')
file.close()
def search():
file=open('stu11.dat','rb')
stu_data=pickle.load(file)
choice='y'
while(choice=='y' or choice=='Y'):
roll=int(input('Enter the roll no. of student which record you want to display :'))
for raw in stu_data:
if raw[0]==roll:
print('Search is successful !')
print('Roll No. of student
:',raw[0]) print('Name of
student :',raw[1])
print('Marks of student :',raw[2])
break
else:
print('Sorry record is not found of rollno :',roll)
choice=input('Press y to search data of another student :')

writeBinary()
search()
12. Write a program to DeleteCustomer() todelete a Customer information from a list of CStack.
The function delete the name of customer from the Stack.
CStack = [“Biraj”, “Manisha”, “Nisha”, “Nitin”, “Suraksha”]

def DeleteCustomer( CStack ):


if (CStack ==[ ]):
print(“There is no Customer, so no need to delete”)
else:
print(“Record deleted:”, CStack.pop( ))

DeleteCustomer(CStack )

13. Python prog. to create menu driven program in python to insert and search the employee
data in employee.csv file

import csv
def create_csv():
file=open('employee.csv','a',newline='')
choice='y'
header=['Name','bank','branch_name','salary']
writer_obj=csv.writer(file,delimiter=',')
writer_obj.writerow(header)
while(choice=='y' or choice=='Y'):
per=0 total=0 name=input('Enter name of
employee : ') bank=input('Enter bank
name name : ') branch=input('Enter
branch name : ') salary=float(input('Enter
salary of employee : '))
row=[name,bank,branch,salary]
writer_obj.writerow(row)

choice=input('Enter y to write data of more student into file : ')


file.close()
def search():
name1=input('Enter name of employee which record you want to search')
file=open('employee.csv','r',newline='')
reader_obj=csv.reader(file,delimiter=',')
for row in reader_obj:
if row[0]==name1:
print('Search is successul')
print('Employee Name
:',row[0]) print('Employee
work in :',row[1])
print('Employee branch is
:',row[2]) print('Employee
Salary is :',row[3]) break
else:
print('Employee data is not found')
file.close()

def displayAll():
file=open('employee.csv','r',newline='')
reader_obj=csv.reader(file,delimiter=',')
next(reader_obj)
for row in reader_obj:
print('*****************Employee Details****************')
print('Employee Name :',row[0])
print('Employee work in :',row[1])
print('Employee branch is :',row[2])

print('Employee Salary is :',row[3])


print('**************************************************')
file.close()
whileTrue:
print('******************************************************’)
print('Press 1 to enter details of employee :')
print('Press 2 to search the employee data :')
print('Press 3 to see the details of all employee :')
print('Press 4 to exit :')
print('******************************************************')
ch=int(input('Enter your choice(1 to 3) :'))
print('******************************************************')
if(ch==1):
create_csv()
elif(ch==2):
search()
elif(ch==3):
displayAll()
elif(ch==4):
break
else:
print('wrong input :')
14. Python program for Insertion in array using bisect module.

import bisect
L1=eval(input('Enter any sorted List :'))
print("Now List is Sorted :",L1)
item=int(input('Enter new element to be inserted :'))
pos=bisect.bisect(L1,item)
bisect.insort(L1,item)
print(item,"inserted at index",pos)
print('The list after inserting element')
print(L1)
15. Python prog. to searching an element in array(List) using binary search technique.

def binarySearch(arr,item):
start=0
end=len(arr)-1
while(start<=end):
mid=int((start+end)/2)
if item==arr[mid]:
returnmid
elif item<arr[mid]:
end=mid-1
else:
start=mid+1
else:
return False

n=int(input('Enter the size of list : '))


arr=[ ]
print(' *** Enter all the values in ascending order ***')
for i in range(n):
a=int(input('Enter element ['+str(i) +'] :'))
arr.append(a)
print('Now List is :',arr)
val=int(input('Enter item which you want to search in array :'))
index=binarySearch(arr,val)
if index is False:
print('Item is not found in list')
else:
print('Item is found in list at position :',index+1)
16. Python program to implement stack using list.

def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if stk==[]:
print("Underflow")
else:
item=stk.pop( )
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def display(stk):
if stk==[]: print("stack is
empty")
else:
top=len(stk)-1 for a
in range(top,-1,-1):
print(stk[a],'<--',end=' ')
# main
stack=[ ]
top=None

while True:
print("stack operations")
print("1.Push") print("2.Pop")
print("3.Display") print("4.Exit")
ch=int(input("Enter your
choice(1-4)")) if ch==1:
item=int(input("Enter item :"))
push(stack,item)
elif ch==2:
item=pop(stack)
print("Item deleted is:",
item)
elif ch==3:
display(stack)
elif ch==4:
break
else:
print('Invalid Choice')
17. '''Small Python program that sends a SQL query to a database and displays
the result from table student store in database.
1) To show all information about the students of History department. To list the 2) names of female students
who are in Hindi department. To list name of 3) student start with s.
'''
import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select * from student where department='history'"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select name from student where department='hindi'"
mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3="select name from student where name like 's%'"
mycursor.execute(sql3)
data=mycursor.fetchall()
print('***Query-3 output***')
for i in data:
print(i)
Q18: '''Small Python program that sends a SQL query to a database and display the result from table
garment store in database.
1) To display garment name and price in ascenging order of price.
2) To display garment name, color and size from table garment.
3) To increment the price of ladies top by 250.

Ans:
import mysql.connector as m
mycon=m.connect(host='localhost',user='root',passwd='kka',database='mysql')
if mycon.is_connected():
print('Successfully connected')
mycursor=mycon.cursor()
sql1="select gname,price from garment order by price"
mycursor.execute(sql1)
data=mycursor.fetchall()
print('***Query-1 output***')
for i in data:
print(i)
sql2="select gname,colour,size from
garment" mycursor.execute(sql2)
data=mycursor.fetchall()
print('***Query-2 output***')
for i in data:
print(i)
sql3="update garment set price=price+250 where gname='Ladies
Top'" mycursor.execute(sql3)
mycon.commit()

mycursor.execute("select * from garment where gname='Ladies Top'")

data=mycursor.fetchall()

print('Updated row is :')

print(data)

19. Solve & execute (i) to (iv) based on SQL connectivity:

Consider the table ITEMS with ITEMNO as primary key.


Table: ITEMS
ITMNO ITEMNAME PRICE
1001 MOUSE 250
1002 SCANNER 2000
1003 PRINTER 7000
1004 MONITOR 6000

i) Write SQL command to create the above table.


ii) Write SQL command to insert the first record.

Write SQL command for (iii) & (iv) using database connectivity with python code:

iii) Display the details of items in alphabetical order of name.


iv) Display the maximum price.

Ans:
i) CREATE TABLE ITEMS (ITEMNO INTEGER PRIMARY KEY, ITEMNAME
VARCHAR(20), PRICE DECIMAL(8,2));
ii) INSERT INTO ITEMS VALUES(1001,’MOUSE’,250);

iii)
import mysql.connector
mydb = mysql.connector.connect( host="localhost", user="root", password="jnv", database="rothak")
mycursor = mydb.cursor()
query1=("SELECT * FROM ITEMS ORDER BY ITEMNAME")
mycursor.execute(query1)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
query2= “SELECT MAX(PRICE) FROM ITEMS"
mycursor.execute(query2)
myresult = mycursor.fetchall()
for x in myresult:
print(x)

Output of the SQL (iii)


ITMNO ITEMNAME PRICE
1004 MONITOR 6000
1001 MOUSE 250
1003 PRINTER 7000
1002 SCANNER 2000

output of the SQL (iv)


MAX(PRICE)
7000

20. Object :- Take the sample of 10 Phishing Emails and write the most common words use in it.

1. Authentication Fail please click on the mentioned


weblink for confirmation.
2. Cancel Request Immediately
3. Urgent Confirmation of online Banking details
4. Save your stuff.
5. Unfortunately Delievery of your order was cancelled.
6. You are expected to login here
7. We regret to inform you that
8. Protect your privacy
9. Your password will expire in 24 hours
10. To settle your bill click here
11. To update your account click on the link
12. To donate the fund in your account
13. Due to credit card error
14. You have received a payment from
15. Click here to activate your account
16. Validate your account
17. Here is your gift card
18. Fund transfer to payer with account ending
………4944
19. Update your facebook account
20. Verify your details

You might also like