Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
70 views

Manu Impro Cs File Python

The document contains descriptions of Python user-defined functions (UDFs) to perform various tasks: 1. Check if a number is prime and display the result. 2. Count and display the number of vowels, consonants, uppercase, lowercase letters in a string. 3. Search a list for an element and return 1 if found, -1 if not found using binary search. 4. Search and count words in a text file. 5. Display lines from a text file starting with certain characters. 6. Count characters in a text file. 7. Count lines ending with vowels in a text file. 8. Copy words from one file to another. 9.

Uploaded by

Ashmit S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Manu Impro Cs File Python

The document contains descriptions of Python user-defined functions (UDFs) to perform various tasks: 1. Check if a number is prime and display the result. 2. Count and display the number of vowels, consonants, uppercase, lowercase letters in a string. 3. Search a list for an element and return 1 if found, -1 if not found using binary search. 4. Search and count words in a text file. 5. Display lines from a text file starting with certain characters. 6. Count characters in a text file. 7. Count lines ending with vowels in a text file. 8. Copy words from one file to another. 9.

Uploaded by

Ashmit S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1. Write a UDF in Python , it will take a number as a function argument .

Function check and display given number if prime or not.


If given number is greater than 1

if num > 1:

for i in range(2, int(num/2)+1):

if (num % i) == 0:

print(num, "is not a prime number")

break

else:

print(num, "is a prime number")

else:

print(num, "is not a prime number")

2.Write a UDF in python,it will take a string as a function argument. Function


will count and display the number of vowels,consonants,uppercase,lowercase
letters.
def fun(s):
v=c=uc=lc=0
m=[]
n=[]
o=[]
l=[]
for i in s:
if i.isupper()==True:
m.append(i)
uc=uc+1
if i.islower()==True:
n.append(i)
lc=lc+1
if i in ("a","e","i","o","u","A","E","I","O","U"):
v=v+1
o.append(i)
else:
c=c+1
l.append(i)

print("The numbers of vowels are",v,o)


print("The numbers of consonants are",c,c)
print("The numbers of uppercase letters are",uc,m)
print("The number of lowercase letters are",lc,n)
s=input("Enter the string to check")
fun(s)

3.Write a UDF in python, it will take two arguments list(sequence of elements) and
finding element . Function search and return 1 if element is present in the given list
otherwise return -1 . Using Binary search.
def fun(L):
num=int(input(“Enter number to search”))
for i in L:
if i==num:
print(num,1)
else:
print(-1)
n=int(input(“enter how many numbers you want to add ”)
L=[]
for i in range(0,n):
s=int(input(“Enter number”))
l.append(s)
fun(L)

4.Write a UDF in python,it will take search me and my words in the text file
DAIRY.TXT.
def fun():
f=open("DAIRY.TXT","r")
s=f.read()
a=0
l=s.split()
for i in l:
if i=="me" or i=="my" or i=="MY" or i=="ME":
a=a+1
print("the numbers of such words are",a)
fun()
5. Write the program in python to read contents of a text file “Places.TXT”and
display all those elements lines on screen which are either starting with “P” or
“S”.
def fun1():
f=open("PLACES.TXT","")
l=f.readlines()
for i in l:
if i[0] in ("P","p","s","S"):
print(i)
f.close()
fun1()

6. Write a User defined function that will read each character in file “IMP.TXT”
should count and display the number of “E”and “U” words present in text file.
def EUcounter():
f=open("IMP.TXT","r")
s=f.read()
a=s.count("E")
b=s.count("e")
c=s.count("u")
d=s.count("U")
print("The numbers of E are",a+b)
print("The numbers of U are",c+d)
f.close()
EUcounter()

7.Write the function in python to count the number of line ending with a
vowelfrom the text file “Story.TXT”.
def fun():
f=open("STORY.TXT","r")
l=f.readlines()
print(l)
a=0
for i in l:
if i[-2] in ("a","e","i","o","u"):
a=a+1
print("The numbers of lines are",a)
f .close()
fun()

8. Write the function copy that will copy all the words starting with uppercase
alphabets from file “FAIPS.TXT” to “DPS.txt”
def copy():
f=open("FAIPS.TXT","r")
p=[]
s=f.read()
l=s.split()
for i in l:
if i[0].isupper==True:
p.append(i)
print(p)
f.close()
w=open("DPS.TXT","w")
w.writelines(p)
w.close()
copy()

9.write a function in python to search a book no.from a binary file


“BOOK.DAT”,assuming the primary file has following type{“Bookno.”,””Book-
name,”Value”}.

def reading():

f=open(“BOOK.DAT”,”wb”)

num=int(input(“Enter the book number to be search”))

try:

while True:

rec=pickle.load(f)

if rec[0]==num:

print(rec)

except EOFError:

10. Write a menu-driven program to perform all the basic operations using dictionary
on student binary file such as inserting, reading, updating, searching and deleting a
record

def insertRec():

rollno = int(input('Enter roll number:'))

name = input('Enter Name:')

marks = int(input('Enter Marks'))

rec = {'Rollno':rollno,'Name':name,'Marks':marks}

f = open('d:/student.dat','ab')

pickle.dump(rec,f)

f.close()

def readRec():

f = open('d:/student.dat','rb')
while True:

try:

rec = pickle.load(f)

print('Roll Num:',rec['Rollno'])

print('Name:',rec['Name'])

print('Marks:',rec['Marks'])

except EOFError:

break

f.close()

def searchRollNo(r):

f = open('d:/student.dat','rb')

flag = False

while True:

try:

rec = pickle.load(f)

if rec['Rollno'] == r:

print('Roll Num:',rec['Rollno'])

print('Name:',rec['Name'])

print('Marks:',rec['Marks'])

flag = True

except EOFError:

break

if flag == False:

print('No Records found')


f.close()

def updateMarks(r,m):

f = open('d:/student.dat','rb')

reclst = []

while True:

try:

rec = pickle.load(f)

reclst.append(rec)

except EOFError:

break

f.close()

for i in range (len(reclst)):

if reclst[i]['Rollno']==r:

reclst[i]['Marks'] = m

f = open('d:/student.dat','wb')

for x in reclst:

pickle.dump(x,f)

f.close()

def deleteRec(r):

f = open('d:/student.dat','rb')

reclst = []

while True:

try:

rec = pickle.load(f)
reclst.append(rec)

except EOFError:

break

f.close()

f = open('d:/student.dat','wb')

for x in reclst:

if x['Rollno']==r:

continue

pickle.dump(x,f)

f.close()

while 1==1:

print('Type 1 to insert rec.')

print('Type 2 to display rec.')

print('Type 3 to Search RollNo.')

print('Type 4 to update marks.')

print('Type 5 to delete a Record.')

print('Enter your choice 0 to exit')

choice = int(input('Enter you choice:'))

if choice==0:

break

if choice == 1:

insertRec()

if choice == 2:

readRec()
if choice == 3:

r = int(input('Enter a rollno to search:'))

searchRollNo(r)

if choice == 4:

r = int(input('Enter a rollno:'))

m = int(input('Enter new Marks:'))

updateMarks(r,m)

if choice == 5:

r = int(input('Enter a rollno:'))

deleteRec(r)

11.Write a function in PYTHON to search for a BookNo from a binary file “BOOK.DAT”,
assuming the binary file is containing the records of the following type:
{"BookNo":value, "Book_name":value}. Assume that BookNo is an integer.

import pickle as p

def fun():

f=open("BOOK.DAT", "rb")

No=input("Enter the BookNo to search: ")

while True:

try:

rec=p.load(f)

for i in rec:

if i[0]==No:

print(i)

except:
break

f.close()

fun()

12. Write a user defined functions implementing the operations

(a) Write a single record to csv

(b) Write all the records in one single line and go to csv.

(c)Display all the contents of csv file.

import csv

def writing():

f=open("Student.csv","w")

obj=csv.writer(f)

obj.writerow("line")

record=[]

line=input("enter the line")

record.append(rec)

if choice=="No":

break

obj.writerows(record)

f.close()

def writing2():

f=open("Student.csv","w")

obj=csv.writer(f)

obj.writerow("admn","name")
record=[]

name=input("enter the line")

admn=int(input("Enter the number"))

record.append(rec)

if choice=="No":

break

obj.writerows(record)

f.close()

def reading():

f=open("student.csv","r")

l=csv.reader(f)

for i in l:

print(i)

f.close()

choice=int(input("Enter the choice"))

if choice==1:

writing()

if choice==2:

writing1():

if choice==3:

reading()
13. Create a CSV file by entering user-id and password, read and search the password
for given userid

import csv

al=["id", "password"]

a=[["useridl", "password1"],["userid2", "password2"],["userid3",


"password3"],["userid4", "password4"],["userid5", "password5"]]

b=input ("Enter username")

myfile=open ("sample.csv", "w+", newline="\n")

myfilel=csv.writer (myfile)

myfilel.writerow(al)

myfilel.writerows (a)

myfile.seek(0)

myfile2=csv.reader (myfile)

for i in myfile2:

if i[0]==b:

print("The paswword is", i[1])

myfile.close()

14. Write a function in python for Push (list) and Pop(List) for performing Push
and Pop operations with a stack.

def push():

s=[]

a=int(input(“Enter number to be push”))

s.append(a)

def pop():

s.pop()
pop()
15. Write a program to create a stack called student, to perform the basic operations
on stack using list. The list contains two data values called roll number and name of
student. Notice that the data manipulation operations are performed as per the rules
of a stack. Write the following functions :
• PUSH ( ) - To push the data values (roll no. and
name) into the stack.
• POP() - To remove the data values from the stack.
• SHOW() - To display the data values from the stack.

Push ()

Pop()

Show()

def push():

s=[]

a=int(input(“Enter number to be push”))

s.append(a)

def pop():

s.pop()

pop()
ABC Infotech Pvt. Ltd. needs to store, retrieve and delete
the records of its employees. Develop an interface that
provides front-end interaction through Python, and
stores
and updates records using MySQL.
16.
(a) Write a UDF to create a table ‘EMPLOYEE’ through
MySQL- Python Connectivity.
(b) Write a UDF to add/insert employee data into the
‘EMPLOYEE’ table through MySQL-Python
Connectivity.
(c) Write a UDF to fetch and display all the records from
EMPLOYEE table .
(d) Write a UDF to update the records of employees by
increasing salary by 1000 of all those employees who
are getting less than 80000.
(e) Write a UDF to delete the record on the basis of
Employee eno.
Write a menu driven program to perform all operations.

import mysql.connector as con

def createTable():

db=con.connect(host='localhost',user="root",password="",database="emp")

cur=db.cursor()

cur.execute("create table EMPLOYEE(eno int(5),name varchar(30),age


int(3),salary float(9,2),doj date,address varchar(30))")

db.commit()

db.close()

def insert():

db=con.connect(host='localhost',user="root",password="",database="emp")

cur=db.cursor()

eno=int(input("Enter Eno of employee: "))

name=input("Enter Name of employee: ")

age=input("Enter Age of employee: ")

sal=int(input("Enter Salary of employee: "))

doj=input("Enter Date of Joining of employee (YYYY-MM-DD): ")


address=input("Enter Address of employee: ")

cur.execute("insert into EMPLOYEElues


({},'{}',{},{},'{}','{}')".format(eno,name,age,sal,doj,address))

db.commit()

db.close()

def display():

db=con.connect(host='localhost',user="root",password="",database="emp")

cur=db.cursor()

cur.execute("select * from EMPLOYEE")

r=cur.fetchall()

for i in r:

print(i)

print()

db.commit()

db.close()

def update():

db=con.connect(host='localhost',user="root",password="",database="emp")

cur=db.cursor()

cur.execute("update EMPLOYEE set salary=salary+1000 where salary<80000")

db.commit()

db.close()
def delete():

db=con.connect(host='localhost',user="root",password="",database="emp")

cur=db.cursor()

eno=int(input("Enter eno of employee: "))

cur.execute("delete from EMPLOYEE where eno={}".format(eno))

db.commit()

db.close()

You might also like