0% found this document useful (0 votes)
5 views60 pages

output

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 60

1.

Arithmetic operators - to implement operators like +,-,*,/,//%

print('Arithmetic Operators')
ch='yes'
while(ch=='yes'):
result=0
val1=float(input('Enter first value:'))
val2=float(input('Enter second value:'))
op=input('Enter any one operator(+,-,*,/,%,//):')
if op=='+':
result=val1+val2
elif op=='-':
result=val1-val2
elif op=='*':
result=val1*val2
elif op=='/':
result=val1/val2
elif op=='%':
result=val1%val2
elif op=='//':
result=val1//val2
else:
print('Enter the correct given operator:')
print('The result:',result)
ch=input('Do you want to continue?(yes/no):')
if ch=='no':
break
OUTPUT:
Arithmetic Operators
Enter first value:50
Enter second value:25
Enter any one operator(+,-,*,/,%,//):+
The result: 75.0
Do you want to continue?(yes/no):yes
Enter first value:52
Enter second value:22
Enter any one operator(+,-,*,/,%,//):-
The result: 30.0
Do you want to continue?(yes/no):yes
Enter first value:50
Enter second value:27
Enter any one operator(+,-,*,/,%,//):*
The result: 1350.0
Do you want to continue?(yes/no):yes
Enter first value:58
Enter second value:14
Enter any one operator(+,-,*,/,%,//):/
The result: 4.142857142857143
Do you want to continue?(yes/no):yes
Enter first value:200
Enter second value:4
Enter any one operator(+,-,*,/,%,//):%
The result: 0.0
Do you want to continue?(yes/no):yes
Enter first value:44
Enter second value:4
Enter any one operator(+,-,*,/,%,//)://
The result: 11.0
Do you want to continue?(yes/no):no

2.creating a menu driven program to find factorial and sum of list of numbers
using function
def Factorial(n):
F=1
if n<0:
print("Sorry, we cannot take Factorial for Negative number")
elif n==0:
print("The factorial of 0 is 1")
else:
for i in range(1, n+1):
F=F*1
print("The Factorial of",n, "is:",F)
def Sum_List(L):
Sum=0
for i in range(n):
Sum=Sum+L[i]
print("The Sum of List is:", Sum)

#Main Program

print("1. To Find Factorial")


print ("2. To Find sum of List elements")
op=int(input("Enter your choice:"))

if op==1:
n=int(input("Enter a number to find Factorial:"))
Factorial(n)

elif op==2:
L=[]
n=int (input("Enter how many elements you want to store in List?:"))
for i in range (n):
el=int (input())
L.append(el)
Sum_List(L)
OUTPUT:
1. To Find Factorial
2. To Find sum of List elements
Enter your choice:1
Enter a number to find Factorial:2
The Factorial of 2 is: 1

1. To Find Factorial
2. To Find sum of List elements
Enter your choice:2
Enter how many elements you want to store in List?:7
10
25
40
55
70
95
100
The Sum of List is: 395

3.creating a python program to implement mathematical functions


import math
def Square(num):
sq=math.pow(num,2)
return sq
def Log(num):
sq=math.log10(num)
return sq
def Quad(x,y):
sq=math.sqrt(x**2+y**2)
return sq
print('THe square of a number is:',Square(5))
print('The log of a number is:',Log(10))
print('The Quad of a number is:',Quad(5,2))
OUTPUT:
The square of a number is: 25.0
The log of a number is: 1.0
The Quad of a number is: 5.385164807134504

4. creating a python program to implement string functions


C=str(input("Enter sentence :"))
a=input("enter the spacing :")
print ("The string entered is a word ",C.isalpha())
print("The string entered in lower case:",C.lower())
print("The string entered is in lower case:",C.islower())
print ("The string entered in lower case :",C.upper())
print("The string entered is in lower case:",C.isupper())
print("The string entered after removing the space from left side:",C.lstrip())
print("The string entered after removing the space from right
side:",C.rstrip())
print("The string entered contains whitespace:",C.isspace())
print("The string entered is titlecased :",C.istitle())
print("The string entered after joining with ",a,":",a.join(C))
print("The string entered after swaping case:",C.swapcase())

OUTPUT:
Enter sentence :'Python is a programming Language'
enter the spacing :
The string entered is a word False
The string entered in lower case: 'python is a programming language'
The string entered is in lower case: False
The string entered in lower case : 'PYTHON IS A PROGRAMMING LANGUAGE'
The string entered is in lower case: False
The string entered after removing the space from left side: 'Python is a
programming Language'
The string entered after removing the space from right side: 'Python is a
programming Language'
The string entered contains whitespace: False
The string entered is titlecased : False
The string entered after joining with : ' P y t h o n i s a p r o g r a m m i n
g Language'
The string entered after swaping case: 'pYTHON IS A PROGRAMMING
lANGUAGE'
5. Text file - to copy one file to another
print('---TEXT FILE---')
file=open('recordsample.txt','r')
lines=file.readlines()
file.close()
file=open('csc.txt','w')
file1=open('output.txt','w')
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print('All lines that contains ''a'' character has been removed in csc.txt file')
print('All lines that contains ''a'' character has been saved in output.txt file')
file.close()
file1.close()
OUTPUT:

--TEXT FILE---
All lines that contains a character has been removed in csc.txt file
All lines that contains a character has been saved in output.txt file
6. Text file - to read file and display each word separated by #
print("----TEXT FILE----")
file=open("recordsample.txt","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()
OUTPUT:

----TEXT FILE----
I#shall#be#telling#with#a#sigh#
Somewhere#ages#and#ages#hence:#
Two#roads#diverge#in#a#wood,#and#I#
I#took#the#one#less#travelled#by#
-ROBERT#FROST#
7. Text file - to read file and display number of vowels , consonants , uppercase , lowercase characters in the
file

print("----TEXT FILE----")
file=open("recordsample.txt","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
if(ch.isupper()):
upper_case_letters+=1
if(ch in ["a","e","i","o","u"]):
vowels+=1
elif(ch in ['b','c','d','f','g','h',,'j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels:",vowels)
print("Consonants",consonants)
print("lower_case_letters:",lower_case_letters)
print("upper_case_letters:",upper_case_letters)

OUTPUT:

----TEXT FILE----
Vowels: 38
Consonants 58
lower_case_letters: 96
upper_case_letters: 16
8. Binary file - to create a student data and search for a data
print("---BINARY FILE---")
import pickle
student_data={}
list_of_students=[]
no_of_students=int(input("Enter number of students:"))
for i in range(no_of_students):
student_data["roll_no"]=int(input("Enter student rollno:"))
student_data["name"]=input("Enter student name:")
list_of_students.append(student_data)
student_data={}
file=open("student_data.dat","wb+")
pickle.dump(list_of_students,file)
print("Data inserted sucessfully")
file.close()
while True:
file=open("student_data.dat","rb+")
rollno=int(input("Enter rollno to be searched:"))
list_of_students=pickle.load(file)
found=False
for student_data in list_of_students:
if student_data["roll_no"]==rollno:
print(student_data["name"],"Found in file")
found=True
if(found==False):
print("student data not found please try again")
found=True
ch=input("Do you want to continue?(yes/no):")
if ch=="no":
break
file.close()
OUTPUT:
---BINARY FILE---
Enter number of students:4
Enter student rollno:1
Enter student name:ANK
Enter student rollno:2
Enter student name:BALA
Enter student rollno:3
Enter student name:RAM
Enter student rollno:4
Enter student name:SAM
Data inserted sucessfully
Enter rollno to be searched:4
SAM Found in file
Do you want to continue?(yes/no):yes
Enter rollno to be searched:2
BALA Found in file
Do you want to continue?(yes/no):no

9. Binary file - to create a student data and update it


print("---BINARY FILE---")
import pickle
def Create():
Z=open("Marks.dat",'ab')
op='y'
while op=='y':
ROLL_NO=int(input('Enter Roll No:'))
NAME=input("Enter Name:")
MARKS=int(input("Enter Marks:"))
L=[ROLL_NO,NAME,MARKS]
pickle.dump(L,Z)
op=input('Do you want to add another students detail(y/n):')
Z.close()
def Update():
Z=open("Marks.dat",'rb+')
number=int(input('Enter student Roll no to modify marks:'))
found=0
try:
while True:
pos=Z.tell()
s=pickle.load(Z)
if s[0]==number:
print("The searched Roll No is found and details are:",s)
s[2]=int(input('Enter New mark to be updated:'))
Z.seek(pos)
pickle.dump(s,Z)
found=1
Z.seek(pos)
print('Mark updated Succesfully and Details are:',s)
break
except:
Z.close()
if found==0:
print('The searched Roll no is not found')
Create()
Update()
OUTPUT:
---BINARY FILE---
Enter Roll No:1
Enter Name:Ankit
Enter Marks:90
Do you want to add another students detail(y/n):y
Enter Roll No:2
Enter Name:Bala
Enter Marks:92
Do you want to add another students detail(y/n):y
Enter Roll No:3
Enter Name:Pinaki
Enter Marks:87
Do you want to add another students detail(y/n):y
Enter Roll No:4
Enter Name:Nikhil
Enter Marks:96
Do you want to add another students detail(y/n):y
Enter Roll No:5
Enter Name:Shantanu
Enter Marks:95
Do you want to add another students detail(y/n):n
Enter student Roll no to modify marks:1
The searched Roll No is found and details are: [1, 'Ankit', 90]
Enter New mark to be updated:91
Mark updated Succesfully and Details are: [1, 'Ankit', 91]

10. CSV file - to create CSV file and display record


print("CSV PROGRAM")
import csv
f=open("CSC.csv","w+",newline="")
CSV_writer=csv.writer(f)
ch="yes"
while ch=="yes" or ch=="Yes":
empno=input("Enter the id of the employee:")
emp_name=input("Enter the name of the employee:")
designation=input("Enter the designation of employee:")
CSV_writer.writerow([empno,emp_name,designation])
ch=input("do you want to continue? (yes/no)")
if ch=="no" or ch=="No":
print("end of the data")
f.seek(0)
csv_reader=csv.reader(f)
for line in csv_reader:
print(line)
f.close()
OUTPUT:
CSV PROGRAM
Enter the id of the employee:001
Enter the name of the employee:HARISH
Enter the designation of employee:MANAGER
do you want to continue? (yes/no)yes
Enter the id of the employee:002
Enter the name of the employee:SURESH
Enter the designation of employee:HR
do you want to continue? (yes/no)yes
Enter the id of the employee:003
Enter the name of the employee:RAMESH
Enter the designation of employee:ASSISTANT MANAGER
do you want to continue? (yes/no)yes
Enter the id of the employee:004
Enter the name of the employee:RAHUL
Enter the designation of employee:INTERN
do you want to continue? (yes/no)no
end of the data
['001', 'HARISH', 'MANAGER']
['002', 'SURESH', 'HR']
['003', 'RAMESH', 'ASSISTANT MANAGER']
['004', 'RAHUL', 'INTERN']
11.CSV file - create a file by entering user-id and password , read and search the password for the given user-
id
print("---CSV FILE---")
import csv
# User-id and password list
List = [["nikhil", "137789"],
["ankit", "263486"],
["pinaki", "257758"],
["shantanu", "377487"],
["bala", "001787"]]

# opening the file to write the records


f1=open("User information.csv", "w", newline="\n")
writer=csv.writer(f1)
writer.writerows(List)
f1.close()
# opening the file to read the records
f2=open("User information.csv", "r")
rows=csv.reader(f2)
userld = eval(input("Enter the user-id: "))
flag = True
for record in rows:
if record[0]==userld:
print("The password is: ", record[1])
flag = False
break
if flag:
print("User-id not found")
OUTPUT:
---CSV FILE---
Enter the user-id: "shantanu"
The password is: 377487

12. Dictionary update


print('---DICTIONARY UPDATE ---')
def fun(d,k):
value2=eval(input('enter the value:'))
d[k]=value2
print('updated dictionary:',d)
x=int(input('number of pairs in dictionary:'))
dic={}
fori in range(x):
key=eval(input('enter a key:'))
value=eval(input('enter a value:'))
dic[key]=value
print('original dictionary:',dic)
a=(eval(input('enter the key whose value you want to change:')))
fun(dic,a)
OUTPUT:
---DICTIONARY UPDATE ---
number of pairs in dictionary:3
enter a key:'hello'
enter a value:1
enter a key:'hi'
enter a value:2
enter a key:'welcome'
enter a value:3
original dictionary: {'hello': 1, 'hi': 2, 'welcome': 3}
enter the key whose value you want to change:'welcome'
enter the value:7
updated dictionary: {'hello': 1, 'hi': 2, 'welcome': 7}

13. Random Numbers


print('Random number generator')
import random
while True:
choice=input('Enter(c) for roll dice or press any other key to quit:')
if choice!='c':
break
n=random.randint(1,200)
print(n)
OUTPUT:
Random number generator
Enter(c) for roll dice or press any other key to quit:c
127
Enter(c) for roll dice or press any other key to quit:c
58
Enter(c) for roll dice or press any other key to quit:c
13
Enter(c) for roll dice or press any other key to quit:c
63
Enter(c) for roll dice or press any other key to quit:c
98
Enter(c) for roll dice or press any other key to quit:c
196
Enter(c) for roll dice or press any other key to quit:v

14. User defined module


def area(l,b):
return l*b
def perimeter(l,b):
return 2*(l+b)
def ke(m,v):
return 1/2*(m*v**2)
def pe(m,he):
return m*he*9.81
def vo(l,b,h):
return l*b*h

import fun
from fun import area
from fun import perimeter
from fun import ke
from fun import pe
from fun import vo
print('****simple scientific calculator****')
print('----enter all the quantity in SI units----')
l=int(input('enter the length:'))
b=int(input('enter the width:'))
h=int(input('enter the height:'))
m=int(input('enter the mass:'))
v=int(input('enter the velocity:'))
he=int(input('enter the height at which object is situated:'))
print('area is',area(l,b))
print('perimeter is',perimeter(l,b))
print('kinetic energy is',ke(m,v))
print('potential energy is',pe(m,he))
print('volume is',vo(l,b,h))
OUTPUT:
****simple scientific calculator****
----enter all the quantity in SI units----
enter the length:20
enter the width:30
enter the height:17
enter the mass:250
enter the velocity:27
enter the height at which object is situated:17
area is 600
perimeter is 100
kinetic energy is 91125.0
potential energy is 41692.5
volume is 10200

15. Linear search


print("----LINEAR SEARCH----")
def fun(l,x):
count=0
for i in range(0,len(l)):
if l[i]==x:
print('found location:',i)
count+=1
print('frequency of element:',count)
a=eval(input('enter a list:'))
b=eval(input('enter element to be searched:'))
fun(a,b)
OUTPUT:
---LINEAR SEARCH----
enter a list:[1,2,3,4,5,6,7]
enter element to be searched:7
found location: 6
frequency of element: 7

16. Binary search


print('----BINARY SEARCH----')
def fun(l,a):
count=0
low=0
high=len(l)-1
while low<=high:
mid=int((low+high)/2)
if a==l[mid]:
count+=1
return('Element found,Index:','Frequency:',count)
elif a<l[mid]:
high=mid-1
else:
low=mid+1
x=eval(input('Enter a list:'))
y=eval(input('enter the element to search:'))
print(fun(x,y))
OUTPUT:
----BINARY SEARCH----
Enter a list:[2,4,6,8,10,12,14]
enter the element to search:8
('Element found,Index:', 'Frequency:', 1)
----BINARY SEARCH----
Enter a list:[2,4,6,8,10,12,14]
enter the element to search:7
None

17. Phishing Emails


file=open(r"email.txt","r")
content=file.read()
max=0
max_occuring_word=""
occurences_dict={}
words=content.split()
for word in words:
count=content.count(word)
occurences_dict.update({word:count})
if (count>max):
max=count
max_occuring_word=word
print("Most occuring word is:",max_occuring_word)
print("Number of times it is occuring:",max)
print("frequency of other words is:")
print(occurences_dict)
OUTPUT:
Most occuring word is: a
Number of times it is occuring: 41
Frequency of other words is:
{'Hey': 1, 'Educators,': 1, 'Many': 1, 'funding': 2, 'agencies': 1, 'often': 1,
'work': 2, 'in': 11, 'highly': 1, 'specific': 3, 'areas': 1, 'and': 5, 'announce': 1,
'RFA': 1, '(funding': 1, 'proposal)': 1, 'for': 2, 'a': 41, 'need': 3, 'budget,': 1,
'but': 1, 'then': 1, 'there': 1, 'are': 2, 'few': 1, 'that': 2, "let's": 1, 'you': 8,
'decides': 1, 'amongst': 1, 'an': 9, 'array': 1, 'of': 6, 'opportunities': 1, 'let': 4,
'define': 1, 'the': 6, 'total': 1, 'budget': 2, 'your': 4, 'need/s,': 1, 'based': 2, 'on':
5, 'working.': 1, 'In': 1, "today's": 1, 'newsletter': 1, 'we': 1, 'will': 1, 'be': 2,
'covering': 1, 'one': 1, 'such': 1, 'grant,': 1, 'lets': 1, 'decide': 2, 'goal': 1, 'allow':
1, 'to': 5, 'submit': 1, 'application': 1, 'needs.': 1, 'You': 1, 'may': 1, 'choose': 1,
'appreciate': 1, 'efforts': 1, 'our': 5, 'team': 1, 'by': 2, 'simply': 1, 'buying': 1,
'us': 1, 'coffee': 1, 'becoming': 1, 'part': 1, 'happiness': 1, 'all': 2, 'around': 1,
'initiative.': 1}
18. Stack
def push():
a=int(input('enter the element which you want to push:'))
stack.append(a)
return a
def pop():
if stack==[]:
print('stack empty..')
else:
print('deleted element is:',stack.pop())
def display():
if stack==[]:
print('stack empty...')
else:
for i in range(len(stack)-1,-1,-1):
print(stack[i])
stack=[]
print('stack operation')
print('************')
choice='yes'
while choice=='yes':
print('1.push')
print('2.pop')
print('3.display')
print('************')
opt=int(input('enter your choice'))
if opt==1:
push()
elif opt==2:
pop()
elif opt==3:
display()
else:
print('wrong input')
choice=input('do you want to continue?(yes/no):')
OUTPUT:
enter the element which you want to push:5
do you want to continue?(yes/no):yes
1.push
2.pop
3.display
************
enter your choice:1
enter the element which you want to push:7
do you want to continue?(yes/no):yes
1.push
2.pop
3.display
************
enter your choice:2
deleted element is: 7
do you want to continue?(yes/no):yes
1.push
2.pop
3.display
************
enter your choice:3
5
do you want to continue?(yes/no):no
19. SQL Commands Exercise - 1

AIM: To write Queries for the following Questions based on the given table

(a) Write a Query to Create a new database in the name of "STUDENTS"


mysql> CREATE DATABASE STUDENTS;
Query OK, 1 row affected
(b) Write a Query to Open the database "STUDENTS"
mysql>USE STUDENTS;
Database changed
(c) Write a Query to create the above table called: STU
mysql>CREATE TABLE STU(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.
mysql> SHOW DATABASES;
(e) Write a Query to List all the tables that exists in the current database
mysql> SHOW TABLES;

(f) Write a Query to insert all the rows of above table into STU table.
mysql> INSERT INTO STU VALUES (1,'Arun','M', 24,'COMPUTER','1997-01-10',
120);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES (2,'Ankit','M', 22,'PHYSICS','1998-03-11',
250);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES (3,'Akash','M',25,'HISTORY','1999-07-
07',300);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES(4,'Anusha','F',27,'ENGLISH','1998-09-
19',210);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES(5,'Umesh','M',26,'HISTORY','1995-05-
07',240);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES(6,'Usha','F',29,'COMPUTER','1992-02-
22',270);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES(7,'Yukesh','M',23,'COMPUTER','1996-02-
07',145);
Query OK, 1 row affected
mysql> INSERT INTO STU VALUES(8,'Usha','F',24,'ENGLISH','1994-05-05',175);
Query OK, 1 row affected
(g) Write a Query to display all the details of the Employees from the above
table 'STU'.
mysql> select * from STU;

(h) Write a query to Rollno, Name and Department of the students from STU
table
mysql>SELECT ROLLNO,NAME,DEPT FROM STU;
20. SQL Commands Exercise - 2

AIM: To write Queries for the following Questions based on the given table:

(a) Write a Query to select distinct Department from STU table.


mysql>SELECT DISTINCT(DEPT) FROM STU;

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


mysql>SELECT * FROM STU WHERE DEPT='HISTORY';

(c) Write a Query to list name of female students in Hindi Department


mysql> SELECT NAME FROM STU WHERE DEPT='HINDI' AND GENDER='F';
(d) Write a Query to list name of the students whose ages are between 18 to
20.
mysql> SELECT NAME FROM STU WHERE AGE BETWEEN 18 AND 20;

(e) Write a Query to display the name of the students whose name is starting
with 'A'
mysql> SELECT NAME FROM STU WHERE NAME LIKE 'A%';

(f) Write a query to list the names of those students whose name have
second alphabet 'n' in their names.
mysql> SELECT NAME FROM STU WHERE NAME LIKE '_N%';
21. SQL Commands Exercise - 3

AIM: To write Queries for the following Questions based on the given table:

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


mysql> DELETE FROM STU WHERE ROLLNO=8;
Query OK, 1 row affected

(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.
mysql> UPDATE STU SET FEES=170 WHERE ROLLNO=1 AND FEES<130;
Query OK, 1 row affected

(c) Write a Query to add a new column Area of type varchar in table STU
mysql> ALTER TABLE STU ADD AREA VARCHAR(20);
Query OK, 7 rows affected
(d) Write a Query to Display Name of all students whose Area Contains NULL .
mysql> SELECT NAME FROM STU WHERE AREA IS NULL;

(e) Write a Query to delete Area Column from the table STU.
mysql> ALTER TABLE STU DROP AREA

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


mysql> DROP TABLE STU;
22. Write a program to integrate SQL with python by importing mysql
module to create, insert and display the employee details.
import mysql.connector as ms
con=ms.connect(host="localhost",user="root",passwd="1234567",
database="Company")
cur=con.cursor()
cur.execute("create table owner(own_id varchar(20),oname char(20),profit
varchar(25))")
print("table created successfully")

while True:
own_id=input("enter the owner id of the owner:")
oname=input("enter the name of owner:")
profit=input("enter the profit of the owner:")
query="insert into owner values('{}','{}','{}')".format(own_id,oname,profit)
cur.execute(query)
con.commit()
print("row inserted successfully")
ch=input("do you want to enter more records?(yes/no)")
if ch=="no":
break
cur.execute("select*from owner")
data=cur.fetchall()
for i in data:
print(i)
print("total number of rows retrived=",cur.rowcount)
OUTPUT:
table created successfully
enter the owner id of the owner:1
enter the name of owner:Nikhil
enter the profit of the owner:20000
row inserted successfully
do you want to enter more records?(yes/no)yes
enter the owner id of the owner:2
enter the name of owner:Vishwa
enter the profit of the owner:30000
row inserted successfully
do you want to enter more records?(yes/no)yes
enter the owner id of the owner:3
enter the name of owner:Yashwanth
enter the profit of the owner:25000
row inserted successfully
do you want to enter more records?(yes/no)no
('1', 'Nikhil', '20000')
('2', 'Vishwa', '30000')
('3', 'Yashwanth', '25000')
total number of rows retrived= 3
23. Write a program to integrate SQl with python by importing mysql module to update and
display the employee details.

import mysql.connector as ms
con=ms.connect(host="localhost",user="root",passwd="1234567",
database="employee")
cur=con.cursor()
cur.execute("create table employeee(EMP_ID varchar(10),ENAME
char(10),SALARY int)")
print("table created successfully")
while True:
emp_id=input("enter the employeee id of the worker:")
ename=input("enter the name of worker:")
salary=int(input("enter the salary of the worker:"))
query="insert into employeee
values('{}','{}','{}')".format(emp_id,ename,salary)
cur.execute(query)
con.commit()
print("row inserted successfully")
ch=input("do you want to enter more records? (yes/no)")
if ch=="no":
break
cur.execute("select*from employeee")
data=cur.fetchall()
for i in data:
print(i)
print("total number of rows retrived=",cur.rowcount)
OUTPUT:
table created successfully
enter the employeee id of the worker:100
enter the name of worker:Sam
enter the salary of the worker:20000
row inserted successfully
do you want to enter more records? (yes/no)yes
enter the employeee id of the worker:101
enter the name of worker:Ram
enter the salary of the worker:30000
row inserted successfully
do you want to enter more records? (yes/no)yes
enter the employeee id of the worker:103
enter the name of worker:Ron
enter the salary of the worker:40000
row inserted successfully
do you want to enter more records? (yes/no)no
('100', 'Sam', 20000)
('101', 'Ram', 30000)
('103', 'Ron', 40000)
total number of rows retrived= 3
24. Write a program to integrate SQl with python by importing mysql module to create,alter and
display the student details.

import mysql.connector as ms
con=ms.connect(host="localhost",user="root",passwd="1234567",database=
"sch")
cur=con.cursor()
cur.execute("create table student(ROLL_NO int,STUDENT_NAME
char(25),CLASS int)")
print("table created successfully")
cur.execute("alter table student add section char(4)")
print("column created succesfully")
while True:
roll_no =int(input("Enter the roll number="))
stu_name=input("enter the name of the student=")
Class =int(input("enter the class of student="))
section=input("enter the section of the student=")
query="insert into student values({},'{}',
{},'{}')".format(roll_no,stu_name,Class,section)
cur.execute(query)
con.commit()
print("row inserted succesfully")
ch=input("do you want to enter more records?(yes/no)")
if ch =="no":
break
cur.execute("select*from student")
data=cur.fetchall()
for i in data:
print(i)
print("total number of rows retrieved=",cur.rowcount)
OUTPUT:
table created successfully
column created succesfully
Enter the roll number=1001
enter the name of the student=Ankit
enter the class of student=12
enter the section of the student=A
row inserted succesfully
do you want to enter more records?(yes/no)yes
Enter the roll number=1002
enter the name of the student=Arnav
enter the class of student=12
enter the section of the student=A
row inserted succesfully
do you want to enter more records?(yes/no)yes
Enter the roll number=1003
enter the name of the student=Rakesh
enter the class of student=12
enter the section of the student=B
row inserted succesfully
do you want to enter more records?(yes/no)no
(1001, 'Ankit', 12, 'A')
(1002, 'Arnav', 12, 'A')
(1003, 'Rakesh', 12, 'B')
total number of rows retrieved= 3

25. Write a program to integrate SQl with python by importing mysql module to delete and
display the student details.

print("---DELETE AND DISPLAY---")


import mysql.connector as ms
con=ms.connect(host="localhost",user="root",passwd="1234567",database=
"sch")
cur=con.cursor()
query="delete from student where ROLL_NO=1003"
cur.execute(query)
con.commit()
cur.execute("select*from student")
data=cur.fetchall()
for i in data:
print(i)
print("total no of rows retrieved=",cur.rowcount)
OUTPUT:
---DELETE AND DISPLAY---
(1001, 'Ankit', 12, 'A')
(1002, 'Arnav', 12, 'A')
total no of rows retrieved= 2

You might also like