You are on page 1of 16

Practical Program List (Use functions in your code) with answer-

1. WAP to show functionality of a basic calculator using functions.


def calculator(n1,n2,oper):
if oper=='+':
return n1+n2
elif oper=='-':
return n1-n2
elif oper=='*':
return n1*n2
elif oper=='/':
return n1/n2
elif oper=='//':
return n1//n2
elif oper=='%':
return n1%n2
else:
print('invalid operator..')
return 0
num1=float(input('enter first number:'))
num2=float(input('enter second number:'))
op=input('input operator among +,-,*,/,//,%:')
print(calculator(num1,num2,op))
***************************************************************************************************************
2. Write a function in python which accept a number from user to return True, if the number is a prime
number else return False. Use this function to print all prime numbers from 1 to 100.
def checkPrime(n):
for i in range (2, n):
if n%i==0:
return False
else:
return True
l=[]
for i in range(1,101):
ans=checkPrime(i)
if ans==True:
l.append(i)
print('Prime numbers between 1 to 100=',l)
*************************************************************************************************************
3. Write a function in python which accept a list of marks of students and return the minimum mark,
maximum mark and the average marks. Use the same function to test.
def checkList(l):
return min(l),max(l),(sum(l)/len(l))
marks=eval(input('enter the marks of students:'))
minList,maxList,avgList=checkList(marks)
print('MAXIMUM MARKS:',maxList)
print('MINIMUM MARKS:',minList)
print('AVERAGE MARKS:',avgList)
***************************************************************************************************************
4. WAP to read a text file “myfile.txt” line by line and display each word separated by a #.
f=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
def show():
try:
while True:
data=f.readline()
data=data.split()
for i in data:
print(i,'#',end='')
except:
f.close()
show()
************************************************************************************************************
5. WAP to read a text file “myfile.txt” and display the number of vowels/ consonants/ uppercase/ lowercase
characters in the file.
def show():
f=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
data=f.read()
vowal=0
cons=0
uper=0
low=0
vowalList=['A','E','I','O','U','a','e','i','o','u']
for i in data:
if i.isalpha()==True:
if i in vowalList:
vowal+=1
else:
cons+=1
if i.isupper():
uper+=1
else:
low+=1
print('number of vowels:',vowal)
print('number of consonants:',cons)
print('number of Capital letters:',uper)
print('number of small letters:',low)
show()
******************************************************************************************************************
6. Remove all the lines that contain the character `a' in a file and write it to another file.
def copyData():
f=open(r'C:\Users\Comp_Lab_II\Desktop\myfile.txt')
f2=open(r'C:\Users\Comp_Lab_II\Desktop\myfile2.txt','w+')
data=f.readlines()
for line in data:
if 'A' not in line:
if 'a' not in line:
f2.write(line)
f2.flush()
f2.seek(0)
data2=f2.read()
print(data2)
f.close()
f2.close()
copyData()

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

print('Frequency of "He" in file=',cntHe)

print('Frequency of "She" in file=',cntShe)

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':

data=eval(input('enter the name and roll number of student:'))

pickle.dump(data,file)

file.flush()

ans=input('want to enter more data? Press Y or N')

ans=ans.lower()

def searchData():

file.seek(0)

try:

found=False

rno=int(input('enter the roll number to search:'))

while True:

data=pickle.load(file)

if data['roll number']==rno:

found=True
nm=data['name']

print('ROLL NUMBER=',rno,' AND NAME=',data['name'])

except:

if found==True:

print('data found..')

else:

print('data not found..')

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:

if float(i[2])>=500 and float(i[2])<=1000:

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':

uid=input('enter user id:')

pwd=input('enter password:')

writerObj.writerow([uid,pwd])

file.flush()

ans=input('want to add more info? y or n..')

ans=ans.lower()

print('data saved successfully..')

def search():

file.seek(0)

uid=input('enter the id to search:')

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 = []

while counter <= 10:

randomNumber = random.randint(1,6)

#print('value of 1 dice ',counter,' time=',randomNumber)

randomNumber2=random.randint(1,6)

#print('value of 2 dice ',counter,' time=',randomNumber2)

myList.append(randomNumber+randomNumber2)

counter = counter + 1

return myList

# Take user input here

print(rolladice())

15. WAP in Python to demonstrate linear search.


def LinearSearch():

list1=eval(input('enter the list of elements:'))

element=eval(input('enter the element to search:'))

found=0

for i in list1:

if i==element:

found=1

position=list1.index(i)+1

else:

continue

if found==1:

print('element found in ',position,' position')

else:

print('element not found..')

LinearSearch()

16. Write a Python program to implement a stack using a list data-structure.


status=[]

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

list1=eval(input('enter the list:'))

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)

list1=eval(input('enter the integer list:'))

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-

Create database school;


ii. For showing list of database-

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

 ALTER TABLE - ADD Column


Query to add email id in table student-
ALTER TABLE Student
ADD Email varchar (255);

 ALTER TABLE - DROP COLUMN


Query to remove email id from table student-
ALTER TABLE Student
DROP COLUMN Email;

 ALTER TABLE – CHANGE COLUMN DATATYPE OR SIZE-


Query to change datatype of column ROLLNO from INT to CHAR and size from 3 to 5 in table student-
ALTER TABLE Student MODIFY ROLLNO CHAR (5);

 ALTER TABLE – DROP a PRIMARY KEY Constraint


Query to remove PRIMARY KEY Constraint from table student-
ALTER TABLE Student
DROP PRIMARY KEY;

 ALTER TABLE – ADD a PRIMARY KEY Constraint


Query to add PRIMARY KEY Constraint to column ROLLNO in table student-
ALTER TABLE Student
ADD PRIMARY KEY (ROLLNO);

 ALTER TABLE - RENAME Column


Query to RENAME column ROLLNO TO RNO in table student-
ALTER TABLE Student
CHANGE ROLLNO RNO INT(3);
ix. Select, From and Where
 Showing all columns and rows from table student-
SELECT * FROM STUDENT;
 Showing only RNO and NAME columns and all rows from table student-
SELECT RNO,NAME FROM STUDENT;
 Showing all columns and rows having PERCENTAGE greater than 60 from table student-
SELECT * FROM STUDENT WHERE PERCENTAGE>60;
 Showing all columns and rows having PERCENTAGE equal to 60 from table student-
SELECT * FROM STUDENT WHERE PERCENTAGE=60;
 Showing all columns and rows having PERCENTAGE equal to 60 or 80 from table student-
SELECT * FROM STUDENT WHERE PERCENTAGE=60 OR PERCENTAGE=80;
 Showing all columns and rows having PERCENTAGE between 60 and 80 from table student
(60 and 80 must be invoved in output) -
SELECT * FROM STUDENT WHERE PERCENTAGE BETWEEN 60 AND 80;
OR
SELECT * FROM STUDENT WHERE PERCENTAGE >= 60 AND PERCENTAGE <=80;
 Showing all columns and rows NOT having THE PERCENTAGE 60 from table student-
SELECT * FROM STUDENT WHERE PERCENTAGE !=60;
 Showing ONLY UNIQUE NAMES with heading (column alias ) ‘UNIQUE NAMES’ from table student-
SELECT DISTINCT NAME AS ‘UNIQUE NAMES’ FROM STUDENT;

x. The SQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

 Query to insert values in all the columns of table student-

INSERT INTO STUDENT VALUES(101,’RAMA’,’1234567892’,18,’JODHPUR’,99.98);

 Query to insert values only in RNO and NAME columns of table student-

INSERT INTO STUDENT (RNO,NAME’) VALUES(102,’JON’);

xi. The SQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.

 Query to change percentage of all students to 100-

UPDATE STUDENT SET PERCENTAGE=100;

 Query to change percentage of Rama to 90-

UPDATE STUDENT SET PERCENTAGE=90 WHERE NAME=’RAMA’;

xii. The SQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

 Query to delete students with rno 101-

DELETE FROM STUDENT WHERE RNO=101;

Query to delete ALL the students


DELETE FROM 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 IN Operator-the IN operator allows us to specify multiple values in


a WHERE clause.The IN operator is a shorthand for multiple OR conditions.
 Showing all columns and rows having PERCENTAGE equal to 60,70,80 or 90 from table
student-
SELECT * FROM STUDENT WHERE PERCENTAGE IN(60,70,80,90);

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:

 The percent sign (%) represents zero, one, or multiple characters


 The underscore sign (_) represents one, single character

 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’;

% and _ are known as wildcard characters in SQL

HANDELLING NULL VALUES


 Showing all details from table student where phone number is not given-
SELECT * FROM STUDENT WHERE PHONE IS NULL;
 Showing only those rows from table student where phone number is given -
SELECT * FROM STUDENT WHERE PHONE IS NOT NULL;

The SQL ORDER BY Keyword

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.

 Showing NAMES IN ASCENDING ORDER from table student-


SELECT NAME FROM STUDENT ORDER BY NAME;
OR
SELECT NAME FROM STUDENT ORDER BY NAME ASC;
 Showing NAMES IN DESCENDING ORDER from table student-
SELECT NAME FROM STUDENT ORDER BY NAME DESC;

The SQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like "find
the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

 SQL statement to lists the number of students in each city:-

SELECT CITY,COUNT(CITY)
FROM STUDENT
GROUP BY CITY;

The SQL HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate
functions.

 SQL statement to lists the number of students in JODHPUR city:-


SELECT CITY,COUNT(CITY)
FROM STUDENT
GROUP BY CITY HAVING CITY=’JODHPUR’;

*******************************************************************************************************
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.

 SQL statement to print total percentage of students in each city :-

SELECT CITY, SUM(PERCENTAGE)


FROM STUDENT
GROUP BY CITY;

The AVG() function returns the average value of a numeric column.

 SQL statement to print average percentage of students in each city :-

SELECT CITY, AVG(PERCENTAGE)


FROM STUDENT
GROUP BY CITY;

The MIN() function returns the smallest value of the selected column.

 SQL statement to print minimum percentage of students :-

SELECT CITY, MIN(PERCENTAGE)


FROM STUDENT;

The MAX() function returns the largest value of the selected column.

 SQL statement to print maximum percentage of students :-

SELECT CITY, MAX(PERCENTAGE)


FROM STUDENT;

The COUNT() function returns the number of rows that matches a specified criterion.

 SQL statement to lists the number of students in each city:-

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

import mysql.connector as mycon


def create_tbl_student():
mydb = mycon.connect(host ="localhost",user ="root",passwd ="123")
mycur = mydb.cursor()
mycur.execute("create database if not exists school1")
mycur.execute("use school1")
query = '''create table if not exists student ( roll varchar(30) primary key,name varchar(30),
dob varchar(30), att varchar(30))'''
mycur.execute(query)
print('TABLE CREATED SUCCESSFULLY...')
create_tbl_student()
****************************************************************************************************************

5. WAP to connect Python with MySQL using database connectivity and perform the following operation on data in
database: Insert record in the table

import mysql.connector as mycon


def insert_tbl_student():
mydb = mycon.connect(host ="localhost",user ="root",passwd
="123",database='school1',charset='utf8')
mycur = mydb.cursor()
roll=input("enter roll no. of the student : ")
name=input("enter name of the student : ")
dob=input("enter year of birth of the student : ")
att=input("enter attendence of the student P/A : ")
query="insert into student values({},'{}','{}','{}')".format(roll,str(name),str(dob),str(att))
mycur.execute(query)
mydb.commit()
print('data inserted successfully...')
insert_tbl_student()
***********************************************************************************************

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

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 delete_Students():
cursor=conn.cursor()
rno=int(input('enter roll no of student to delete:'))
query= cursor.execute('delete from student where rno={}'.format(rno))
conn.commit()
print('DELETED SUCCESSFULLY....')
delete_Students()
***********************************************************************************************************

You might also like