You are on page 1of 42

1. Program to find the sum of odd and even elements in a tuple.

CODE:
t=(1,2,3,4,5,6,7,8,9,10)
odsum=0
evsum=0
for i in t:
if i%2==0:
evsum=evsum+i
else:
odsum=odsum+i
print("sum of even numbers:",evsum)
print("sum of odd numbers:",odsum)
2. Program to return the smallest and biggest elements from a list after sorting.
CODE:
lest=[5,14,3,55,56,7,54,32,75,85]
lest.sort()
print("sorted list:",lest)
print("smallest number:",lest[0])
print("biggest number:",lest[-1])
3. Program to search any given word in a given sentence or string.
CODE:
str=(input("enter the needed string:"))
search_word=(input("enter the word to search for :"))
if search_word in str:
print("the word is in the sentence ")
else:
print("the word is not in the sentence")
4. Write a menu-driven program to create a text file NOTES.txt using the function
CreateP ().Read the text file and display the number of lines which starts with alphabet
‘P’ using function readP ()
CODE:
def creatP():
f=open("NOTESS.txt","a")
while True:
story=input("enter your story:")
f.write(story+"\n")
user=input("add more ? Y/N:")
if user=="n":
break
def readP():
f=open("NOTESS.txt","r")
count=0
data = f.readlines()
for i in data:
if i[0]=="p":
count+=1
elif i[0]=="p":
count+=1
print("no of lines with P as the first letter:",count)
f.close()
def menu():
print("to create text file press 1.")
print("to find the count of sentences with P/p press 2.")
ch=input("enter your choice:")
if ch=="1":
creatP()
if ch=="2":
readP()
menu()
5. Write a menu-driven program to create a text file STORY.txt using the function
Create () and read and count the number of ‘my’ or ‘me’ words present in it using the
function CountMeMy ()
CODE:
def create():
f=open("story.txt", "w")
while True:
story = input("enter the your story :")
f.write (story + "\n")
user = input("add more ? Y/N :")
if user == "n":
break

def CountMeMy():
f=open("story.txt" , "r")
count=0
data =f.read()
words = data.split()
for i in words:
if i=="me":
count+=1
elif i=="my":
count+=1
print("no of lines with me and my :",count)
f.close()
def menu():
print("to create text file press 1.")
print("to find the count of sentences with me and my press 2.")
ch = input("enter your choice :")
if ch=="1" :
create()
if ch=="2" :
CountMeMy()
menu()
6. Reading from a file and displaying the contents by adding ‘#’ character after each
word.
CODE:
f=open ("hashdisplayfile.txt" , "r")
data=f.readlines()
s=""
for i in data:
word=i.split()
for a in word:
s=s+a+"#"
print(s)
f.close
7. Read file contents and display the count of uppercase, lowercase, consonants
and vowels.
CODE:
f=open("Letters.txt","r")
upper=0
lower=0
vow=0
cons=0
data=f.read()
for i in data:
if i in ("AEIOUaeiou"):
vow+=1
else:
cons+=1
for i in data:
if i.isupper():
upper+=1
elif i.islower():
lower+=1
else:
pass
print("count of upper:",upper)
print("count of lower:",lower)
print("count of vowels:",vow)
print("count of consonants:",cons)
f.close()
8. Reading from a text file and writing into a new file only those lines without ‘a’ in it.
CODE: f=open("old_story.txt","r")
f1=open("new_story.txt","w")
for i in f:
if "a" not in i:
f1.write(i)
f.close()
f1.close()
9. Write a program to create a binary file with the structure [name and roll
number,Percentage].and call the function to Search () to search for a given roll
number and display the Values, if not found display appropriate message.
CODE:
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("enter roll number:"))
name = input("enter name:")
per = int(input("enter percentage of marks:"))
student.append([roll,name,per])
ans=input("add more?(Y)/(N)")
pickle.dump(student,f)
f.close()

def search():
f=open('student.dat','rb')
student=[]
student=pickle.load(f)
ans='y'
while ans.lower()=='y':
found=False
r=int(input("enter roll number to search:"))
for s in student:
if s[0]==r:
print("## name is:",s[1],"##")
print("## percentage is:",s[2],"##")
found=True
break
if not found:
print("####sorry! roll number not found#####")
ans=input("search more?(Y)/(N):")
f.close()
search()
10. Write a program to create a binary file with the structure [ name and roll
number,percentage].and call the function to Update() to change the percentage for a
given roll number, if not found display an appropriate message.
CODE:
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll=int(input("enter roll number:"))
name=input("enter name:")
per=int(input("enter percentage of marks:"))
student.append([roll,name,per])
ans=input("add more?(Y)/(N)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student=pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r=int(input("enter roll number to update:"))
for s in student:
if s[0]==r:
print("## name is:",s[1],"##")
print("### current percentage is:",s[2],"###")
m=int(input("enter new percentage:"))
s[2]=m
print("## record updated ##")
found=True
break
if s[0]!=r:
print("#### sorry! roll number not found ####")
ans=input("update more?(Y):")
f.close()
11. Write a program to create a binary file with the structure [name and roll number,
Percentage].and call the function Delete () to delete the details for a given roll number,
if not found display the appropriate message.
CODE:
import pickle def
create():
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll=int(input("enter roll number:"))
name=input("enter name:")
per=int(input("enter percentage of marks:"))
student.append([roll,name,per])
ans=input("add more?(Y)/(N)")
pickle.dump(student,f)
f.close()
create()

def delete():
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
de=False
r=int(input("enter roll number to delete:"))
for s in student:
if s[0]==r:
print("## name is:",s[1],"##")
print("## current percentage is:",s[2],"##")
s.pop()
print("record deleted ...... ")
de=True
break
if not de:
print("####sorry! roll number not found ####")
ans=input("delete more ?(Y):")
f.close()
delete()
12. . A csv file has a structure[ name and roll number, marks].Create a menu driven
program and
call the functions .
a. Create function addCsvFile () to write data into the file
b. Create function readCsvFile() to read and display the data.
CODE:
import csv
def menu():
print("1. Add the Employee details to CSV file ")
print("2. Display Employee details ")
print("3. Exit the program ")
ch=int(input("Enter your choice:"))
if ch==1:
addCsvFile()
elif ch==2:
readCsvFile()
else:
print("Program exit")
def addCsvFile():
Employee=[]
f=open("Employee.csv","w",newline="")
emp=csv.writer(f)
emp.writerow(["Emp_no","Name","Salary"])
while True:
empno=int(input("Enter the Emp_no:"))
empname=input("Enter the Employee Name:")
sal=int(input("Enter the Salary:"))
Employee.append([empno,empname,sal])
ch=input("Do U want to continue: y/n?:")
if ch=='n':
break
emp.writerows(Employee)
f.close()
menu()
def readCsvFile():
f=open("Employee.csv","r")
emp_read=csv.reader(f)
for row in emp_read:
print(row[0],row[1],row[2])
f.close()
menu()
13. Create a CSV file that has a structure[ name and roll number, marks], search the
given name and display the relevant details or appropriate message otherwise.
CODE:
import csv
def menu():
print("1. Add the Student details to CSV file.")
print("2. Search Student details.")
print("3. Exit the program.")
ch=int(input("Enter your choice:"))
if ch==1:
addCsvFile()
elif ch==2:
search()
else:
print("Program exit")
def addCsvFile():
student=[]
f=open("stud.csv","w",newline="")
info=csv.writer(f)
info.writerow(["Name","Roll","Mark"])
while True:
roll_no=int(input("Enter the Roll:"))
stdname=input("Enter the Student Name:")
mark=int(input("Enter the Mark:"))
student.append([roll_no,stdname,mark])
ch=input("Do U want to continue: y/n?:")
if ch=='n':
break
info.writerows(student)
f.close()
menu()

def search():
f=open("stud.csv","r")
data=csv.reader(f)
found = False
r=input("enter the Name:")
for row in data:
if str(row[1])==r:
print("Roll:",row[0])
print("Mark:",row[2])
found = True
continue
if not found:
print("student data not found.")
menu()
menu()
14. Create a CSV file by entering user-id and password, read and search the password
for given user id.
CODE:
import csv
List=[["userid1","pass1"],
["userid2","pass2"],
["userid3","pass3"],
["userid4","pass4"],
["userid5","pass5"]]
f=open ("user_info.csv","w",newline="\n")
writer=csv.writer(f)
writer.writerows(List)
f.close()

f1=open ("user_info.csv","r")
rows=csv.reader(f1)
user_ID=input("enter the id to be searched:")
x=True
for i in rows:
if i[0]==user_ID:
print("the passcode is:",i[1])
x=False
break
if x:
print("invalid id.##not dound##")
15. Write a menu based program to add,delete and display the record of hostel using
list as stack data structure in python. Recod of hostel contains the fields: Hostel
Number,Total Students and Total Rooms.
CODE:
host=[]
ch='y'
def push(host):
hn=int(input("Enter hostel number"))
ts=int(input("Enter Total students"))
tr=int(input("Enter total rooms"))
temp=[hn,ts, tr]
host.append(temp)
def pop(host):
if(host==[]):
print("No Record")
else:
print("Deleted Record is :",host.pop())
def display (host):
l=len(host)
print("Hostel Number\tTotal Students\tTotal Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"It\t",host[i][2])
while(ch=='y' or ch=='Y'):
print("1. Add Record\n")
print("2. Delete Record\n")
print("3. Display Record\n")
print("4. Exit")
op=int(input("Enter the Choice"))
if(op==1):
push(host)
elif(op==2):
pop(host)
elif(op==3):
display(host)
elif(op==4):
break
ch=input("Do you want to enter more(Y/N)")
16. Write a Python Program to integrate MYSQL with Python by inserting records to
Emp table and display the it.
CODE:
import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='password',database='
employees')
if con.is_connected():
cur=con.cursor()
opt='y'
while opt=='y':
No=int(input("Enter Employee Number:"))
Name=input("Enter Employee Name:")
Gender=input("Enter Employee Gender(M/F):")
Salary=int(input ("Enter Employee Salary : "))
Query="INSERT INTO EMP VALUES({},'{}','{}',{})".format(No,Name,Gender,Salary)
cur.execute(Query)
con.commit()
print ("Record Stored Successfully")
opt=input("Do you want to add another employee details(y/n):")
Query="SELECT * FROM EMP";

cur.execute(Query)
data=cur.fetchall()
for i in data:
print(i)
con.close()
17. Write a Python Program to integrate MYSQL with Python to search an Employee
using EMPID and display the record if present in already existing table EMP, if not
display the appropriate message.
CODE:
import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='password',database='
employees')
if con.is_connected():
cur=con.cursor()
print ("_________________________________")
print ("welcome to employee search screen")
print ("_________________________________")
No=int(input("enter employee number to search:"))
Query="SELECT * FROM EMP WHERE EMP={}".format(No)
cur.execute(Query)
data=cur.fetchone()
if data!=None:
print (data)
else:
print ("Record not Found!!!")
con.close()
18. Write a Python Program to integrate MYSQL with Python to search an Employee
using EMPID and update the Salary of an employee if present in the already existing
table EMP, if not display the appropriate message.
CODE:
import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='password',database='
employees')

if con.is_connected():
cur=con.cursor ()
print ("****************************************")
print ("Welcome to Employee detail update Screen")
print("****************************************")
No=int(input("Enter the employee number to Update:"))
Query="SELECT * FROM EMP WHERE EMPID={}".format (No)
cur.execute(Query)
data=cur.fetchone()
if data!=None:
print ("Record found details are:")
print (data)
ans=input ("Do you want to update the Salary of the above employee (y/n) ?:")
if ans=='y' or ans=='Y':
New_Sal=int(input("Enter the New Salary of an Employee:"))
Q1="UPDATE EMP SET SALARY={} WHERE EMPID={}".format(New_Sal,No)
cur.execute(Q1)
con.commit ()
print ("Employee Salary Updated Successfully")
Q2="SELECT * FROM EMP"
cur.execute (Q2)
data=cur.fetchall()
for i in data:
print (i)
else:
print (" Record not Found! !!")
19. Write a Python Program to integrate MYSQL with Python to delete Employee
details using EMPID and, if not existing the EMPID displays the appropriate message.
CODE:
import mysql.connector
con=mysql.connector.connect(host='localhost',username='root',password='retupmoc',databas
e='employees')

if con.is_connected():
cur=con.cursor()
print("****************************************")
print("welcome to employee detail delete screen")
print("****************************************")
no=int(input("enter the employee no. to delete: "))
query="SELECT * FROM EMP WHERE EMPID={}".format(no)
cur.execute(query)
data=cur.fetchone()

if data!=None:
print("record found details are: ")
print(data)
ans=input("do you want to delete the details of the above employee(y/n)?")

if ans=='y' or ans=='Y':
q1="DELETE FROM EMP WHERE EMPID={}".format(no)
cur.execute(q1)
con.commit()
print("employee details deleted successfuly")
q2="SELECT * FROM EMP"
cur.execute(q2)
data=cur.fetchall()
for i in data:
print(i)
else:
print("record not found")
SQL COMMANDS EXERCISE - 1
Write the queries for the following questions based on the given table:

(a) Write a query to create a new database in the name of "SCHOOL"


Sol: mysql> CREATE DATABASE SCHOOL;

(b) Write a query to open the database "SCHOOL"


Sol: mysql> USE SCHOOL;

(c) Write a query to create the above table STUDENT


Sol: mysql> CREATE TABLE STUDENT(Rollno int Primary key,
Name varchar(10),Gender varchar(3), Age int,Dept varchar(15),DOA date,Fees int);
(d) Write a query to list all the existing database names.

Sol: mysql> SHOW DATABASES;

(e) Write a query to List all the tables that exist in the current database.

Sol: mysql> SHOW TABLES;

(f) Write a query to display all the details of the Employees from the above table STUD
Sol: mysql> SELECT * FROM STUD;
(g) Write a query to Rollno, Name and Department of the student ts from STUD table

Sol: mysql> SELECT ROLLNO,NAME,DEPT FROM STUD;


SQL COMMANDS EXERCISE – 2:
Write the queries for the following questions based on the given table Student:

(a) Write a query to select distinct Department from STUD table.

Sol: mysql> SELECT DISTICT(DEPT) FROM STUD;

(b) To show all information about students of History department.


Sol: mysql>SELECT * FROM STUD WHERE DEPARTMENT='HISTORY';
(c) Write a query to list name of female students in Hindi Department.
Sol: mysql> SELECT NAME FROM STUD WHERE DEPARTMENT='HINDI' AND
GENDER='F';

(d) Write a query to list name of the students whose ages are between 18 to 20.
Sol: mysql> SELECT NAME FROM STUD WHERE AGE BETWEEN 18 AND 20;

(e) Write a query to display the name of the students whose name is starting with 'A'.

Sol: mysql> SELECT NAME FROM STUD WHERE NAME LIKE 'A%';
(f) Write a query to list the names of those students whose name have second alphabet
'n' in their names.
Sol: mysql> SELECT NAME FROM STUD WHERE NAME LIKE '_N%';
SQL COMMANDS EXERCISE - 3:
Write the queries for the following Questions based on the given table
Student:

(a) Write a query to delete the details of Roll number is 8.

Sol: mysql> DELETE FROM STUD WHERE ROLLNO=8;

(b) Write a query to change the fess of Student to 170 whose Roll number is 1,
if the existing fess is less than 130.
Sol: mysql> UPDATE STUD SET FEES=170 WHERE ROLL=1 AND FEES<130;
(c) Write a query to add a new column area of type varchar in table STU.

Sol: mysql> ALTER TABLE STUD ADD AREA VARCHAR(20);

(d) Write a query to display name of all students whose Area Contains NULL.

Sol: mysql> SELECT NAME FROM STUD WHERE AREA IS NULL;

(e) Write a query to delete area column from the table STU.

Sol: mysql> ALTER TABLE STU DROP AREA;

(f) Write a query to delete table from Database.

Sol: mysql> DROP TABLE STUD;


SQL COMMANDS EXERCISE - 4
Write the queries for the following questions based on the given table:

(a) To display the total Unit price of all the products whose Dcode as 102.
Sol: mysql> SELECT SUM(UNITPRICE) FROM STOCK GROUP BY DCODE
HAVING DCODE=102;

(b) To display details of all products in the stock table in descending order of Stock date.

Sol: mysql> SELECT * FROM STOCK ORDER BY STOCKDATE DESC;


(c) To display maximum unit price of products for each dealer individually as
per dcode from the table Stock.
Sol: mysql> SELECT DCODE,MAX(UNITPRICE) FROM STOCK GROUP
BY DCODE;

(d) To display the Pname and Dname from table stock and dealers.

Sol: mysql> SELECT PNAME,DNAME FROM STOCK S,DEALERS D WHERE


S.DCODE=D.DCODE;
SQL COMMANDS EXERCISE - 5
Write Queries for the following Questions :

a. Write a query to display cube of 5.

Sol: select pow(5,3);

b. Write a query to display the number 563.854741 rounding off to the next hundred.

Sol: select round(563.854741,-2);

c. Write a query to display "put" from the word "Computer".

Sol: select mid(“Computer”,4,3);


d. Write a query to display today's date into DD.MM.YYYY format.

Sol: select concat(day(now()), concat('.',month(now()),concat('.',year(now())))) "Date";

e. Write a query to display 'DIA' from the word "MEDIA".

Sol: select right("Media",3);

DONE BY : SIPHIN SAMSON


GRADE :12-A

You might also like