Professional Documents
Culture Documents
OR
def copyData():
f=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
f2=open(r'C:\Users\Comp_Lab_II\Desktop\myfile3.txt','w+')
data=f.readlines()
for line in data:
if 'A' not in line and 'a' not in line:
f2.write(line)
f2.flush()
f2.seek(0)
data2=f2.read()
print(data2)
f.close()
f2.close()
copyData()
******************************************************************************************************************
7. Write a program to create a text file and print the lines starting with ‘T’ or ‘P’. (Both uppercase and
lowercase).
#Ans 7 with function
def printData():
f=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
data=f.readlines()
for line in data:
L1=['t','T','P','p']
if line[0] in L1:
print(line)
f.close()
printData()
***********************************************************************************************************
8. Read a text file to print the frequency of the word ‘He’ and ‘She’ found in the file.
#Ans 8
def readHeShe():
file=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
data=file.read()
cntHe=0
cntShe=0
data=data.split()
for i in data:
i=i.lower()
if i=='he':
cntHe+=1
elif i=='she':
cntShe+=1
else:
continue
readHeShe()
9. Create a binary file with name and roll number. Search for a given roll number and display the name, if not found
display appropriate message.
#Ans 9
import pickle
file=open(r'D:\myBinaryFile.bin','ab+')
def inputData():
ans='y'
while ans=='y':
pickle.dump(data,file)
file.flush()
ans=ans.lower()
def searchData():
file.seek(0)
try:
found=False
while True:
data=pickle.load(file)
if data['roll number']==rno:
found=True
nm=data['name']
except:
if found==True:
print('data found..')
else:
file.close()
inputData()
searchData()
10. Create a binary file with roll number, name and marks. Input a roll number and update the marks.
#Ans 10
import pickle
file=open(r'D:\myBinaryFile2.bin','wb+')
def inputData():
ans='y'
while ans=='y':
data=eval(input('enter the name, roll number and marks of student:'))
pickle.dump(data,file)
file.flush()
ans=input('want to enter more data? Press Y or N')
ans=ans.lower()
def updateMarks():
file.seek(0)
try:
rno=int(input('enter the roll number to search:'))
newMarks=int(input('enter new marks'))
while True:
pos=file.tell()
data=pickle.load(file)
if data['roll number']==rno:
data['marks']=newMarks
file.seek(pos)
pickle.dump(data,file)
file.flush()
print('ROLL NUMBER=',data['roll number'],' AND NEW MARKS=',data['marks'])
except:
file.close()
def show():
file=open(r'D:\myBinaryFile2.bin','rb+')
try:
while True:
data=pickle.load(file)
print(data)
except:
file.close()
inputData()
updateMarks()
show()
11. Read a CSV file from hard disc and print all the details on the screen.
import csv
def readCSV():
file=open(r'D:\saurav.csv',newline='\n')
readerObj=csv.reader(file)
for i in readerObj:
print(i)
file.close()
readCSV()
12. Read a CSV file (containing item no, name, rate, QOH) from hard disc and print all the items whose rate is
between Rs 500 and Rs 1000.
import csv
def readCSV():
file=open(r'D:\saurav2.csv',newline='\n')
readerObj=csv.reader(file)
for i in readerObj:
if i[2].isalpha()==True:
continue
else:
print(i[1])
file.close()
readCSV()
13. Create a CSV file by entering user-id and password, read and search the password for given userid.
import csv
file=open(r'D:\saurav3.csv','a+',newline='\n')
def writeCSV():
writerObj=csv.writer(file)
writerObj.writerow(['user-id','password'])
ans='y'
while ans=='y':
pwd=input('enter password:')
writerObj.writerow([uid,pwd])
file.flush()
ans=ans.lower()
def search():
file.seek(0)
readerObj=csv.reader(file)
for i in readerObj:
if i[0]==uid:
print('password=',i[1])
writeCSV()
search()
file.close()
14. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Throw the two dices for 10 times and print their total.
import random
def rolladice():
counter = 1
myList = []
randomNumber = random.randint(1,6)
randomNumber2=random.randint(1,6)
myList.append(randomNumber+randomNumber2)
counter = counter + 1
return myList
print(rolladice())
found=0
for i in list1:
if i==element:
found=1
position=list1.index(i)+1
else:
continue
if found==1:
else:
LinearSearch()
def Push_element(list1):
status.append(list1)
def Pop_element():
while len(status)>0:
print(status.pop())
else:
print('Stack Empty..')
for i in range(5):
Push_element(list1)
Pop_element()
17. WAP to pass an integer list as stack to a function and push only those elements in the stack which are divisible
by 7.
status=[]
def Push_element(list1):
for i in list1:
if i% 7==0:
status.append(i)
print(status)
Push_element(list1)
Database Management
1. Queries using Create database, Show databases, Use, Create table, Show Tables, Describe, Rename, Alter, Select,
From, Where, Insert, Update commands
i. Creating database the query will be-
Show databases;
iii. For accessing database-
Use school;
iv. For creating table student with rollno , name, phone,age,city and percentage columns. Age must be
greater than or equals to 16. Use all possible constraints-
CREATE TABLE STUDENT(ROLLNO INT(3) PRIMARY KEY, NAME VARCHAR (15) NOT NULL, PHONE CHAR(10)
UNIQUE, AGE INT (2) DEFAULT 16, CITY VARCHAR (15),PERCENTAGE FLOAT(5,2),CHECK (AGE>=16));
v. For showing list of tables-
Show Tables;
vi. For showing structure of table-
Describe STUDENT;
OR
DESC STUDENT;
vii. For Renaming the table STUDENT TO XII_CS_STUDENTS-
ALTER TABLE STUDENT RENAME TO XII_CS_STUDENTS;
viii. Alter Command
Query to insert values only in RNO and NAME columns of table student-
2. Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY, GROUP BY, HAVING
* The SQL SELECT DISTINCT Statement-The SELECT DISTINCT statement is used to return only
distinct (different) values. Inside a table, a column often contains many duplicate values; and
sometimes we only want to list the different (distinct) values.
Showing ONLY UNIQUE NAMES from table student-
SELECT DISTINCT NAME FROM STUDENT;
* The SQL BETWEEN Operator- the BETWEEN operator selects values within a given range. The values
can be numbers, text, or dates. The BETWEEN operators is inclusive: begin and end values are
included.
Showing all columns and rows having PERCENTAGE between 60 and 80 from table student
(60 and 80 must be involved in output) -
SELECT * FROM STUDENT WHERE PERCENTAGE BETWEEN 60 AND 80;
The SQL LIKE Operator -The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
Showing only NAME columns and rows where values of name that start with "a" from
table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘A%’;
Showing only NAME columns and rows where values of name that ends with "a" from
table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘%A’;
Showing only NAME columns and rows where values of name that contains "a" in any of
the position from table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘%A%’;
Showing only NAME columns and rows where values of name contains "a" at second
position from table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘_A%’;
Showing only NAME columns and rows where values of name that start with "a" and are at
least 2 characters in length from table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘A_’;
Showing only NAME columns and rows where values of name that contains only 5
characters in length from table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘_____’’(5 times underscore sign is
used)’;
Showing only NAME columns and rows where values of name that start with "a" and ends
with “o” from table student-
SELECT NAME FROM STUDENT WHERE NAME LIKE ‘A%O’;
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
The GROUP BY statement groups rows that have the same values into summary rows, like "find
the number of customers in each country".
SELECT CITY,COUNT(CITY)
FROM STUDENT
GROUP BY CITY;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.
*******************************************************************************************************
3. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( ) –All are known as
aggregate functions and used with multiple rows but return single answer-
The SUM() function returns the total sum of a numeric column.
The MIN() function returns the smallest value of the selected column.
The MAX() function returns the largest value of the selected column.
The COUNT() function returns the number of rows that matches a specified criterion.
SELECT CITY,COUNT(CITY)
FROM STUDENT
GROUP BY CITY;
****************************************************************************
4. WAP to connect Python with MySQL using database connectivity and perform the following operation on data in
database: Create a table in database
5. WAP to connect Python with MySQL using database connectivity and perform the following operation on data in
database: Insert record in the table
6. WAP to connect Python with MySQL using database connectivity and perform the following operation on data in
database: Fetch records from the table using fetchone( ), fetchall() and fetchmany( ).
import mysql.connector as sqltor
import pandas as pd
def fetchRecords():
mconn=sqltor.connect(host='localhost',user='root',
passwd='mysql',database='company',charset='utf8')
if mconn.is_connected():
print("CONNECTED SUCCESSFULLY")
cursor=mconn.cursor()
cursor.execute("SELECT* FROM dept")
data1=cursor.fetchone()
count=cursor.rowcount
print("TOTAL NUMBER OF ROWS=",count)
print(data1)
data2=cursor.fetchmany(3)
count2=cursor.rowcount
print("TOTAL NUMBER OF ROWS=",count2)
print(data2)
data3=cursor.fetchall()
count3=cursor.rowcount
print("TOTAL NUMBER OF ROWS=",count3)
print(data3)
for row in data3:
print(row)
mconn.close()
else:
print ("ERROR IN CONNECTIVITY")
fetchRecords()
*******************************************************************************************************
7. WAP to connect Python with MySQL using database connectivity and perform the following operation on data in
database: Update record in the table
import mysql.connector as sqlc
conn=sqlc.connect(host='localhost',user='root',passwd='mysql',database='school_management',charset
="utf8")
if conn.is_connected():
print("CONNECTED SUCCESSFULLY")
else:
print("NOT CONNECTED")
def update_In_Students():
cursor=conn.cursor()
col=input('enter the column to update:')
newval=input('enter new values:')
rno=int(input('enter roll no of student to be update:'))
query= cursor.execute('update student set {}="{}" where rno={}'.format(str(col),str(newval),rno))
conn.commit()
print('UPDATED SUCCESSFULLY....')
update_In_Students()
*****************************************************************************************************
8. WAP to connect Python with MySQL using database connectivity and perform the following operation on
data in database: Delete record from the table