0% found this document useful (0 votes)
12 views34 pages

Cs Practical 2024

The document outlines various programming tasks and functions to be implemented in Python, including checking for prime numbers, manipulating lists, performing stack operations, and handling text and binary files. It provides code snippets for each task, demonstrating how to read files, count characters, and manage data structures. Additionally, it covers CSV file operations and Python-SQL connectivity tasks.

Uploaded by

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

Cs Practical 2024

The document outlines various programming tasks and functions to be implemented in Python, including checking for prime numbers, manipulating lists, performing stack operations, and handling text and binary files. It provides code snippets for each task, demonstrating how to read files, count characters, and manage data structures. Additionally, it covers CSV file operations and Python-SQL connectivity tasks.

Uploaded by

Moksha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 34
INDEX €-é 7 Hn? © ¢ &! Zz Oo PROGRAMS PAGE | NO. FUNCTIONS ste ee Write a function to check whether the given no. is prime or not. Write a function to add alternate elements of a list. Write a function to accept a list as parameter and print all the even number in the list. Write a function to accept a list as parameter and multiply all the odd elements by 5. Write a function to accept two numbers as parameter and find greater number between two. STACKS Write a program to implement various stack operations without 6 using built-in function. dee Sw ee ea ees __| built-in function. | consists of A,E,I. Write a program to implement various stack operations using Assume a dictionary and write a function to add new element in the stack. Add only those elements from the dictionary whose value TEXT FILE Write a function to read a text file and print words starting with iin reverse order. 11 Write a function AMCount() in python, which should read each character of a text file and count and display the occurrence of alphabets 'A' and 'M'(in both cases). 12 Write a function to count number of lowercase characters present in a text file. 13 Write a function to read content and count the number of line starting with either 'l' or'M' ina text file. 14 Write a function to read lines ofa oo y . + | binary file and display words which has less then 4 characters. BINARY FILE Write a program to read the - structure [rollno.,name,marks].Write a function createfile() to input record and add to stu.dat. content of a binary file ‘book.dat’. | | Given a binary file stu.dat with __ Write a program search_rec() which takes book no. as parameter and displays its record. Structure of binary file- [book no., book name,price]. GE CECCECEL ECE CE CHEE CE EEF SEE GLEEE < < Write a function countrec() to count and display the records of binary file ‘stu.dat’ where percentage is above 75. Structure of file is - | [admin_no.,name,percentage]. Write a program to count the no. | of buses whose destination = | ‘delhi’ from binary file ‘bus.dat’. Structure of file=[bus no.,start 19 point.destination] CSV FILE Write a program to read a csv file. 21 Write a program to write data ina csv file. 22 Write a program to search any empno from the above program and display name,salary and an appropriate message if not found. 23 PYTHON-SQL CONNECTIVITY Write a program in python to Create a database in mysql. 24 Write a python program to create sql table 25 Peer Fa CU Write a python program to enter values in sql table. 26 Write a python program to select with condition from sql table 27 NO < SQL QUERIES Sesesesesesees oF FST SSESESE SETS SHCHEEECET ECE FGEEPSE PEE ESE’ ES SE 1,FUNCTIONS (1) Write a function to check whether the given no. is prime or not. def isprime(n): p=True d=2 while d<=pow(n,0.5) and p: if n%d=: p=False else: dt=1 return p t=int(input("enter no. to check")) print(isprime(t)) QUTPUT: “crea” or “ice fer more infomation, = RESTART: C\Weers\asha\Destoppp\py szeeeeeevnnsseenee 4367 esse RESTART: C/\Ueere\Yetmi\Destep\p\S py svetenvosssnensone® RESTART: C\WearsWashv\Deshoopyp\S py ssseeessssseceseee son RESTART: C\Uers\eth\Oestop pS py 2220008 on RESTART: C:\Usre\Ya\Destop\p\5.p7 seEeeE EE EEE DE dE EEEETEEEPEMAMECEEEEEEFESFE (2) Write a function to add alternate elements of a list. def addAlternate(arr): sum=0 for iin range(len(arr)): if 1%: sum+=arr[i] return sum arr=[] n=int(input("enter no of values:")) for i in range(n): it=int(input("enter values:")) arr.append(it) s=print("sum of alternate elements of list:",addAlternate(arr)) OUTPUT: Fle We te Og Optom Minden Hep Python 3.9.5 (tags/v3.9.5:Oa7debd, Moy 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", “copyright”, "credits" or “license()" for more information. === RESTART: C:\Users \Yashvi\AppData\Local\Programs\Python\Python39\fni py ==== ‘enter no of values:5 enter values:90 enter values: 75 enter values:46 enter values:86888 enter values:2 sum of alternate elements of list: 138, sell (3) Write a function to accept a list as parameter and print all the even number in the list. def displaylist(Ist): print("even elements of the list") for i in range(0,len(|st)): if Ist[i]%2==0: print(Ist{i]) Ist1=eval(input("enter the list") displaylist(Ist1) OUTPUT: Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win 32 Type "help", "copyright", “credits” or "license()" for more information. >>> =e5nscssssssssss=== RESTART: C:/Users/Yashvi/Desktop/pp/12, py ================== enter the list{20,11,3,5,7,90,99,45,] even elements of the list 20 90 >>> SoU CC Che ee EEE EEHEEHEEGHEEEOCCEEEOEOCE (4) Write a function to accept a list as parameter and multiply all the odd elements by 5. def displaylist(Ist): for i in range(0,len(Ist)): if Ist[i]%2==1: Ist[i]=Ist[i]*5 \st=eval(input("enter the list")) displaylist(Ist) print("new list",Ist) OUTPUT: Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)} on win 32 Type "help", “copyright”, “credits” or “license()" for more information. enter the list(1, new list (5, 115, >>> | SESRELSCRESCESHEHOOEECECE ECHO ECHO EEC ECEHCECEECEEEE SL (5) Write a function to accept two numbers as parameter and find greater number between two. def greater(n1,n2): if n1>n2: print(n1,"is greater") elif n2>n1: print(n2,"is greater") else: print("numbers are equal") n1=int(input("enter a number:")) n2=int(input("enter another number:")) greater(n1,n2) OUTPUT: RESTART: C:/Users/Yashvi/Desktop/pp/14. py ===: enter a number:: enter another number:7 7 is greater >>> RESTART: C:/Users/Yashvi/Desktop/pp/14.py ===== enter a numbe! enter another number:4 numbers are equal SSS CESCHE SE EFC GES ESF GE 68 OOOO oee oe © « 2.STACKS (1) Write a program to implement various stack operations without using built-in function. stack=[] def getchoice(): print("Menu \n 1.PUSH \n 2.POP \n 3.DISPLAY \n 4.EXIT") choice=int(input("enter choice") return choice def push_item(item): stack.append(item) def pop_item(): global stack item=stack[-1] del stack[-1] return item def dis(): print("elements of stack are:",stack) choice=getchoice() while choice! if choice==1: nint(input(“enter item to push:")) push_item(n) sesesebeE LEE E SESH HSHSESEECE EH ECE EHCTCEESCSCSCEE EES E £ if (len(stack)!=0): n=pop_item() print("popped item:",n) else: print("stack underflow") elif choice==3: if (len(stack)!=0): dis() else: print("stack underflow") else: print("wrong choice") choice=getchoice() OUTPUT: Mena 1.pUSH 2.P0P 3.DISPLAY 4paT enter choice! |enter item to push:5 enter choice? ‘elements of stack are: [5] ‘enter choice? popped item’ 5 SCEELEEEREO SSE SESOOKEESECERC EHEC CGC OC OOSCSS ESS” (2) Write a program to implement various stack operations using built-in functions. stack=[] def getchoice(): print("Menu \n 1.PUSH \n 2.POP \n 3.DISPLAY \n 4.EXIT") choice=int(input("enter choice") return choice choice=getchoice() while choice!=0: if choice==1: nzint(input("enter item to push:")) stack.append(n) elif choice==2: if (len(stack)!=0): n=stack.pop() print(""popped item:",n) else: print("stack underflow") elif choice: if (len(stack)!=0): print("elements of stack are:",stack) else: Ee eel ewer erFrSTVeTeeeee Ge 6 GS SG print("stack underflow" else: print("wrong choice’ choice=getchoice() QUTPUT: ‘s+ RESTART: C-/Users/Yash\/AppData/Lacol/Prograns/Pythan/Python39/sTock3 PY * ‘Menu | 1.PUSH 2PoP S.DISPLAY 4.5qT enter choice ‘ener item fo push Mans push 2 oP S.DISPLAY 4.paT eter choice! enter item to push? Mens 1.PUSH 20° ‘.0ISPLAYy 4.007 enter choice popped item: 2 Fe tie O09 Opes nto ep ‘enter choicet ‘enter item to push:2 ‘Menu 1.PUSH 2.POP 3.DISPLAY 4.5aT enter choice? popped item: 2 ‘Mena 1.PUSH 2.POP 3.DISPLAY 4.5aT ‘enter choice3 elements of stack are: [1 Mena 1.PUSH 2.POP 3.DESPLAY 4.0aT enter choice SSSCECECEE SCE SCECEEE ETC ECSCE CESSES ESSEC SECC (3) Assume a dictionary and write a function to add new element in the stack. Add only those elements from the dictionary whose value consists of A EI. d={'INDIA':'DELHT’, ' ITALY':' ROME’, 'ABC’:'XYZ'} 0) def push(c): for iin d: if ‘A’ in d[i] or E’ in df] or "in di): c.append(d[i]) print(c) push(c) OUTPUT: Python 3.11.4 (tags/v3.11.1:a78450'/Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win 32 Type “help”, “copyright”, “credits” or “license()" for more information. RESTART: C:/Users/Yashvi/Desktop/pp/s1 py SSSeSeseeeSSte CCC EKCECCECEECCECCCECCCE SC ECE Se 3. TEXT FILE (1) Write a function to read a text file and print words starting with iin reverse order. def revtext(): f1=open(C\\Users\\Yashvi\Desktop\\story. txt, 'r') while True: rl=fl.readlines() for lines in rl: words=lines.split() for iin words: if if0]=="i" ] print(r) or if0 else: i print(r) QUTPUT: joo RESTART: C:\Users\Yashvi\ AppData\Local\Programs\Python\Python39\hhw5.py === |moerceci (2) Write a function aMCountt) in python, which should read each character of a text file and count and display the occurrence of alphabets ‘A’ and 'M'(in both cases). def AMCount(): myfile=open("C:\\Users\\Yashvi\\Desktop\\story.txt" , "r") fl=myfile.read() c=fl.count("m") cl=f1.count("M") c2=f1.count("A") ¢3=fL.count("a") sumi=c+cl sum2=c2+c3 print("count of occurrence of m\M is:",sum1) print("count of occurrence of a\A is:",sum2) AMCount() OUTPUT: Fe Se Sa) ig po Winker ap (Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win (32 Type “help", “copyright”, “credits” or “license()" for more information. = RESTART: C:\Users\Yashvi\ AppData\Local\ Programs \Python\Python39\hhw2.py count of occurrence of m\M is: 6 teount of occurrence of a\A is: 9 Mae bbb Sole b bbs eeel el EEE EE (3) Writea function to count number of lowercase characters present in a text file. def loweralpha(): fname=input("enter file name") y — count=0 ) s=0 f1=open(fname,'r') for lines in f1: [1=lines.split () for words in |1: for letter in words: if (letter.islower()): st=1 count=s print("no. of lowercase characters in file:",count) loweralpha() OUTPUT: aren eos) Fie tar Bet Sng Opens rdw Python 3.9.5 (tags/v3.9.5:0a7debd, May 3 2021, 17:27:52) [MSC v.1926 64 bit (AMD64)] on win |32 Type "help", “copyright”, "credits" or “lcense()" for more information RESTART: C:\Users\Yashvi\ AppData\Local\Programs\Python\Python39\hhw6.py === enter file nameC:\Users\Vashvi\Desktop\pp\story. txt no. of lowercase characters in file: 118 Besse seeeoeoeoeeeeoue”’ (4) Write a function to read content and count the number of line starting with either 'l' or 'M' ina text file. def count(): fname=input("enter file name") f1=open(fname,'r') count=0 r=0 s=0 for line in f1: if line[O]=='i e1 if line[0]=='m' or line[0]==" st=1 count=r+s print("The no. of lines starting with M or I:",count) count() OUTPUT: 7 mE SHe38S 0x Fie Ee Sel Deng Opts Haden Hip Python 3.9.5 (tags/v3.9.5:Oa7debd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win | 32 Type "help", "copyright", "credits" or "license()" for more information. >>» RESTART: C:\Users\Yashvi\AppData\Local\Programs\Python\Python39\hhw7.py === enter file nameC:\Users\Yashvi\Desktop \pp\story. txt The no. of lines starting with M or I: 7 | >>> » (5) Write a function to read lines ofa binary file and display words which ) has less then 4 characters. ; def displaywords(): fname=input("enter file name") fl=open( fname, 'r') for line in f1: words=line.split() fori in words: if len(i)<3: print(i) displaywords() OUTPUT: === RESTART: C:\Users\Yashvi\ AppData\L¢cal\Programs\Python\Python39\hhw4.py === | enter file nameC:\Users\Yashvi\Desktop\pp\story. txt | : | : a be 4, BINARY FILE (1) Write a program to read the content of a binary file ‘book.dat’ mport pickle with open("book dat”, 'rb’) as 1 fname=(} try while True ftname=pickle.load(f1) print(fname) except, f1.close() OUTPUT: (2) Given a binary file stu.dat with structure [rollno.,name,marks].Write function createfile() to input record and add to stu.dat. import pickle def createfile(): with open("stu.dat",'ab') as f1: rec=0 mo=int(input("enter roll no.")) name=input("enter student name") marks=int(input("enter marks") rec=[rno,name,marks] pickle.dump(rec,f1) print("data saved") ans=input("enter more") createfile() OUTPUT: Python 3.9.5 Wop 9 50eTdebd, May 32021, 17:27:52) OASCv.1928 64 it (ANDES) on win 2 “Type “hey capri, “reer cent" fr mere infomation (3) Write a Program search_rec() which takes book no. as parameter and displays its record. Structure of binary file- [book no., book name, price]. import pickle def search_rec(n): with open("book.dat","rb") as f1: c=0 try: while True: rec=pickle.load(f1) if rec(0}==n: ctl print(rec{0],rec{1],rec[2}) except: fl.close() return c me=search_rec(2) print("total",m) QUTPUT: Feet pm te Python 3.9.5 (tags/v3.9.5:0a7debd, May 3 2021, 17:27:82) [MSC v.1928 64 bit (AMDS4)] on win32 ‘Type “help”, “copyright”, “credits” or "license(" for more information. sexes RESTART: C:\Users\Yashvi\Appbara\Local\Programs\Python\Python39\7.py ===== 2 rstggg 4536 2 moonlight 832 2 moonlight 382 2 wat 829 total 4 (4) Write a function countrec() to count and display the records of binary file ‘stu.dat’ where percentage is above 75. Structure of file is - [admin_no.,name,percentage]. def countrec(): with open(" stu.dat","rb") as f1: num=0 try: while True: rec=pickle.load(f1) if rec[2]>75: num+=1 print(rec[0],rec[1},rec[2}) except: fi.close() return num countrec() - OUTPUT: ie tae Set Gg Open inte ep Python 3.9.5 (tage/v3.9.5:Oa7debd, May 3 2021, 17:27:52) (MSC v.1928 64 bit (AMD64)} 32 Type “help”. “copyright, "credits" or “license()" for more information. === RESTART: C:\Users\Yashvi\ AppData\Local\Programs\Python\Python39\bn2.py ===» 375392 sgjsr 82.0 8052 ceufeja 434.0 8032 hrgark 80.0 480 hrehgh 834.0 76 hhh 78.0 1 raj 78.0 1 raj 89.0 2 sakshi 90.0 3 rashmi 88.0 7 uwou 832.0 ) Write a program to count the no. of buses whose destination = ‘delhi’ ‘om binary file ‘bus.dat’, Structure of file=[bus no.,start point.destination] f countrec(): with open("bus.dat" , 'rb') as f1: count=0 try: while True: rec=pickle.load(f1) if rec[2]=='delhi': count+=1 print(rec{0},rec[1],rec[2]) except: fi.close return count print(“the no. of buses with destination delhi -”,countrec()) OUTPUT: Fe ik big Opes Wn = Python 3.9.5 (tags/v3.9.5:0a7debd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win 32 Type "help", “copyright”, “credits" or “license()" for more information. |ESTART: C:\Users\Vashvi\ AppData\Local\Programs\Python\Python39\bn3.py ==*= eg atharyata dey 2.” nanci delhi 482 mumbai d the no, of buses with destination deli : 4 3. CSV FILE (1) Write a program to read a csv file. import csv , with open("C:\\Users\\Yashvi\\Desktop\\excel1.csv") as cf: } print("%10s"%"empno." , "%20s"%"empname', "%415s"%" salary") print(" for row in myfilereader: print("%10s"%row(0] , "%20s"%rowl1] , "%615s"%row(2]) print Fe {oe Dat tg Opin tee Hap Python 3.9.5 (togs/v3.9.5:Oa7debd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win 32 ‘Type "help", “copyright”, “credits” or “license()" for more information, === RESTART: C:\Users\Yashvi\Appbata\ Local \Programs\Python\Python39\csvl.py === ‘empno emprame salary * iwirg 2e40 23 rulge eas 8 herghiw 8200 9230 Kou 364 2230 wuf 824 (2) Write a program to write data in a csv file. import csv with open("myfile.csv","a") as csvfile: mywriter=csv.writer(csvfile,delimiter: empno=int(input("enter employee no.")) put("enter employee name") sal=int(input(“enter salary")) mywriter.writerow([empno,ename,sal]) print("data saved") ans=input("enter more") OUTPUT: Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win 32 Type “help”, “copyright”, "credits" or “license()” for more information. RESTART: C:/Users/Yashvi/Desktop/pp/csv2.py = enter employee no.9 enter employee nameraj enter salary7800 data saved enter moren (3) Write a program to search any empno from the above program and display name,salary and an appropriate message if not found. import csv with open(""myfile.csv","r") as csvfile: myreader= csv.reader(csvfile,delimiter=",") found=False eint(input("enter employee no. to search") for row in myreader: if (len(row)!=0): if int(row[0])==e: print("name",row[1]) print("'salary",row(2]) found=True break else: print("employee no. not found") OUTPUT: Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win 32 Type "help", “copyright”, “credits” or “license()" for more information. = RESTART: C:\Users\Yashvi\Desktop\pp\esv3.py =: enter employee no. to search2 name wljw eae 2342 6, PYTHON - SQL NNECTIVITY (1) Write a program in python to create a database in mysq]. import mysql.connector mydb=mysql.connector.connect(host="localhost’, password='root', user='root') mycursor=mydb.cursor() mycursor.execute("create database myd'" OUTPUT: ete a ea connection id is 12 SCN Sree me Ty tsge ia eet ce copyright (c) 2008, 2021, Oracle and/or its affiliates. Pees state ere ie mae oat rae te Cee coe Other names may be trademarks of their respective Reet ones eee ae ) Write a python program to create sql table. port mysql.connector ydb=mysql.connector.connect(host='localhost', password='root', user='root', jatabase='myd') ycursor=mydb.cursor() ycursor.execute("create table student( roll_no integer(110), name rchar(20),sports varchar(20)) ") Cet ea Can aera coe Sooip Cal Co MeL eels eM ToC re tcar ia setae Tele eee ates Tate ote ea eettC ee Ler omens asast Claim ey eens Crea Te ee es eee ure eee ote Tables_in_myd | ean CeCe) — re 3) Write a python program to enter values in sql table. import mysql.connector ydb= ysql.connector.connect{host="localhost password='root’, user='root', latabase='myd') ycursor=mydb.cursor() ="insert into student(roll_no,name,sports) values(%s,%S,%5)" al=( 1, Jessica’, 'volleyball’) ycursor.execute(q,val) mydb.commit() OUTPUT: fee Se Uh Write a python program to select with condition from sql table. rt mysql.connector =mysql.connector.connect(host="localhost', password='root’, user='root', base='myd') irsor=mydb.cursor() elect * from student where sports='cricket™ ursor.execute(q) it(mycursor.fetchall()) Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win 32 Type “help”, “copyright”, “credits” or “license()” for more information. RESTART: C:/Users/Yashvi/Desktop/ppimys4.py (5, raj’, ‘cricket’)] Z.SQL QUERIE. red trademark of Oracle Corporation and/or its Se Mo eas tas as Ord CRU coals Ms ia Caen See ed oe See epee ssa ee te Age He eotoa a anwesha | mumbai | 200500 | akshita | mumbai | 400000 | cant eee rae etal eeu ere ee ee pee ee ee a es Bees et =, ee eee Uitte Hee) DE ees artes cee oT mr eo a Bs Tsar) lelcome to th Cram olan ae LPs ol eae e UEC Ask reer peaet PAS Oeco peat tat sD Ales USCS Lear SSM Tae TL yet eas oh EET Tes Peete nas Cox mses aa alee tatiana s Chere yea t es vaeeeC lees: PULL RU Valle cane andr ences tare ts ced alles SOMO UML s(n 7 ean ee cu sen dare ae CT eee ae Der ea Fes Pree esti DEC RES Ctadeee tye aslo tN ts e + salary | gender | eer. S z s 1 | anwesha | mumbai | 200500 | akshita | mumbai ec) | Ty bangalore | 10000 | rad bet) bangalore | 490000 Mesures fer) ecu th Cr) Sted mysql> select * from employee order by salary desc; pre hr eFC la a Cl spa) mumbai | 400000 riddhima | bangalore | 400000 ET er) Ler be | 200500 fae e Sia) dehradun | 69500 faal-lulst-be | 6eeee bangalore | 10000 Siete eietaiaiaied cen | city | salary | gender | Hs lie Pee) <4 eb oe 0 ey bat) a | S ottteeieiisiated Sees | elaciatciieated Seeded oo 1 row in set (@.0@ sec) 2 rows in set (0.00 sec)

You might also like