COMPUTER SCIENCE WITH PYTHON
AIM:
To write a python program to find factorial of the entered number using functions.
ALGORITHM:
Step 1: Start the program execution Step
2: Read the value of number Step
3: Call the function factorial(number) Step
4: Initialize fact=1 Step
5: Check for loop , if the condition is true go to
step 6 else go to step 7 Step 6: Calculate fact =fact*i
Step 7: Return fact to result
Step 8: Print result
Step 9: Stop the program execution
SOURCE CODE:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input("enter the number"))
result = factorial(num)
print("The factorial of", num, "is", result)
OUTPUT:
enter the number 5
The factorial of 5 is 120
2. FIBONACCI SERIES
AIM:
To write a python program to enter the number of terms and to print the Fibonacci
Series.
ALGORITHM:
Step 1: Start the program execution
Step 2: Read the value of n
Step 3: Initialize a=0,
b=1 , sum=0 and
count=1
Step 4: Check if count<=n
if the condition is true go to step 6
else goto step 7
Step 5: Print sum
Step 6: Increment count by 1 and assign a=b, b=sum and sum=a+b Step
7: stop the program execution
SOURCE CODE:
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:") while count <
nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
OUTPUT:
HOW MANY TERMS? 10
FIBONACCI
SEQUENCE:
13
21
34
RESULT:
Thus, the python program to print the Fibonacci series for n term is done successfully
and the output is verified
3. RANDOM NUMBER GENERATION
AIM:
To write a python program to generate random number between 1 and 6
using random module.
ALGORITHM:
Step 1: Start the program execution Step 2: Read the value of n
Step 3: Initialize s=0
Step 4: for i=1 to n do
If(n%i)==0 then s=s+i
Step 5:if s==n
Print “given number is perfect”
Else print “given number is not perfect”
Step 6: stop the program execution
SOURCE CODE:
import random
n = random.randint(1,6)
guess = int(input("Enter a number between 1 to 6:")) if n
== guess:
print("Congratulations!!!!"
) else :
print("Sorry,Try again\n Original number is",n)
OUTPUT:
Enter a number between 1 to 6:2
Sorry,Try again Original number is 5
Enter a number between 1 to 6:1
Congratulations!!!!
4.PALINDROME USING STRINGS
Program:
str=input("Enter a string: ")
l=len(str)
p=l-1
index=0
while(index<p):
if((str[index])==str[p]):
index=index+1
p=p-1
else:
print("String is not a palimdrome")
break
else:
print("String is a palindrome")
OUTPUT:
Enter a string: MOM
String is a palindrome
5. ARMSTRONG NUMBER
num=int(input("Enter any number: "))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=(digit)**3
temp//=10
if num==sum:
print("The given number",num,"is an armstrong number")
else:
print("The given number",num,"is not an armstrong
number")
OUTPUT:
Enter any number: 153
The given number 153 is an armstrong number
6. READING A FILE LINE BY LINE
AIM:
To write a python program to read a text file line by line and display each
word separated by a '#'
ALGORITHM:
Step 1: Start the program execution
Step 2: Open myfile.txt in read mode
Step 3: Check for loop, if the condition is true go to step 4 else
go to step 7
Step 4: Split words in line using split( ) function
Step 5: Check for loop, if the condition is true go to step 5 else
go to step 3
Step 6: print the value of i and add ‘#’ symbol
Step 7: Stop the program execution
SOURCE CODE:
filein = open("myfile2.txt",'r')
line =" "
while line:
line = filein.readline()
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
OUTPUT:
myfile2.txt
hello this is python programming
Hello#this#is#python#programming
RESULT:
Thus, the python program to read a text file line by line and display each word
separated by a '#' is done successfully and the output is verified.
7. COUNTING VOWELS/ CONSONANTS/ UPPERCASE/LOWERCASE
CHARACTERS AND DIGITS IN A FILE
AIM:
To write a python program to read a text file and display the number of
vowels/ consonants/ uppercase/lowercase characters and other than character and digit in
the file.
ALGORITHM:
Step 1: Start
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using read() method
Step 4:Write the logic for counting the Vowels,Consonants,Upper case
letters,Lower case letters using islower(),isupper(),ch in [‘a’,’e’,’i’,’o’,’u’],
ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
Step 5: Close the file using close() method
Step 6: Print the Counting data.
Step 7: Stop
SOURCE CODE:
filein = open("Myfile2.txt",'r')
line= filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other
=0
print(line)
for ch in line:
if ch.isupper():
count_up
+=1
if ch.islower(): count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' 'and ch =='\n':
count_other += 1
print("Digits",count_digit) print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
OUTPUT:
Hello this is python programming
hello1234
united@ups
Digits 4
Vowels: 14
Consonants: 28
Upper Case: 1
Lower Case: 41
other than letters and digit: 2
RESULT:
Thus, the python program to read a text file and display the number of vowels/
consonants/ uppercase/lowercase characters and other than character and digit in the file
is done successfully and the output is verified.
8. TEXT FILE HANDLING (COPYING ALL LINES STARTING WITH ”T” INTO ANOTHER
FILE)
def copyspecificlines():
with open('E:\\mystory5.txt','r')as F: with
open("E:\\mystory7.txt",'w')as f:
reader=F.readlines() for
line in reader:
if line[0]=='T':
f.writelines(line)
print("The content is copied successfully")
copyspecificlines()
OUTPUT:
The content is copied successfully.
9. FINDING THE LONGEST WORD IN A FILE
AIM:
To write a python program to find longest word from text file.
ALGORITHM:
Step 1: Start the program execution
Step 2:Open myfile2.txt in read mode
Step 3:Find the length of the word.
Step 4: Split words in line using split( ) function
Step 5: Check for loop, if the condition is true go to step 5 else
go to step 3.
Step 6: print the longest word.
Step 7: Stop the program execution.
SOURCE CODE:
fin = open("myfile2.txt","r")
str = fin.read()
words = str.split()
max_len = len(max(words, key=len)) for word in words:
if len(word)==max_len:
longest_word =word
print(longest_word)
OUTPUT:
Programming.
RESULT:
Thus the python program to find longest word from text file is done successfully
and the output is verified.
10. Writing and Reading in a Binary File.
ALGORITHM:
STEP 1:Import pickle module
STEP 2:Assign an empty dictionary to variable member STEP
3:Define a function writing_Binary()
STEP 4:Open the file with read mode
STEP 5:Get the member no and name from the user and assign it to a dictionary STEP
6:Define a function read_Display_Binary()
STEP 7:Open the binary file with read mode
STEP 8:Using load function read the content of the file and print it STEP
9:Create a menu with options
1.Write the data in binary file
2.Read the data from the file
3.Exit
STEP 10:Get the choice from the user and call the function STEP
11:Stop the program
PROGRAM:
import pickle
Member = {}
def Writing_Binary():
with open('member.dat','wb') as wbfile: while
True:
Mno = int(input('Enter the member no: ')) name
= input('Enter the name: ') Member['MemberNo']
= Mno Member['Name'] = name
pickle.dump(Member,wbfile)
ch = input('Do you want to continue y/n :') if ch
== 'n':
print('Binary File writing is over')
break
def Read_Display_Binary():
with open('member.dat','rb') as rbfile: try:
while True:
Member = pickle.load(rbfile)
print(Member)
except EOFError:
print('Finished reading binary file')
while True:
print(' ')
print('Menu Driven Programming')
print(' ')
print('1. To create and store binary data')
print('2. To read the binary data') print('3. To
exit')
ch = int(input('Enter your choice: ')) if ch
== 1:
Writing_Binary()
elif ch == 2:
Read_Display_Binary()
elif ch == 3:
break
OUTPUT:
Menu Driven Programming
1. To create and store binary data
2. To read the binary data
3. To exit
Enter your choice: 1
Enter the member no: 101
Enter the name: ccc
Do you want to continue y/n :y
Enter the member no: 203
Enter the name: hhh
Do you want to continue y/n :n
Binary File writing is over
Menu Driven Programming
1. To create and store binary data
2. To read the binary data
3. To exit
Enter your choice: 2
{'MemberNo': 101, 'Name': 'ccc'}
{'MemberNo': 203, 'Name': 'hhh'}
Finished reading binary file
Menu Driven Programming
1. To create and store binary data
2. To read the binary data
3. To exit
Enter your choice: 3
11. Search and display using binary file
Aim: To create a binary file to store member no and member name. Given a member no, display its
associated name else display appropriate error message.
ALGORITHM:
STEP 1:Import pickle module
STEP 2:Assign an empty dictionary to a variable member STEP
3:Define a function store_Binary_info()
STEP 4:Open the binary file with append mode
STEP 5:Get the member no and name from the user and assign it to a dictionary
STEP 6:Define a function Search_file()
STEP 7:Open the file with read mode
STEP 8:Get the mno to be searched from the user
STEP 9:Load the content of the binary file and assign it to a member
STEP 10:Using the if condition check whether the mno is present in the file STEP 11:If
condition is true,print it
Else print not found
STEP 12:Call the function
STEP 13:Stop the program
Program:
import pickle
Member = {}
def Store_binary_info():
with open('member.dat','ab') as wbfile: while
True:
Mno = int(input('Enter the member no: ')) name
= input('Enter the name: ') Member['MemberNo']
= Mno Member['Name'] = name
pickle.dump(Member,wbfile)
ch = input('Do you want to continue y/n :') if ch
== 'n':
print('Binary File writing is over')
break
def Search_display_binary_info():
with open('member.dat','rb') as rbfile:
mno = int(input('Enter the member no to be searched:')) try:
while True:
Member = pickle.load(rbfile)
if Member['MemberNo'] == mno:
print(Member)
break except
EOFError:
print('MemberNo not found')
Store_binary_info()
Search_display_binary_info()
Output:
Enter the member no: 8002
Enter the name: Sukanya
Do you want to continue y/n :y
Enter the member no: 8003 Enter
the name: Archana
Do you want to continue y/n :y
Enter the member no: 8004 Enter
the name: Prasath
Do you want to continue y/n :n
Binary File writing is over
Enter the member no to be searched:8003
{'MemberNo': 8003, 'Name': 'Archana'} Enter the
member no to be searched:8008 MemberNo not
found
Result: The above program has been executed successfully.
12.
EX.NO:12
UPDATING A BINARY FILE
Date:
AIM:
To write a python program to create and update the student details in a
binary file.
ALGORITHM:
Step 1: Start the program execution
Step 2: Import the pickle module and open the file “StudentRecord.dat” in read mode
Step 3: Read the student details using load function
Step 4: Check if stud[“SrollNo”] = =roll, if the condition is true go to step 5 else go to
step 7
Step 5: Print stud and set found=True
Step 6: Check if found==False then go to step 9 else go to step 10 Step
7: Print “Record not found”
Step 8: Print “Record updated” Step
9: Stop the program execution
SOURCE CODE:
import pickle
def Writerecord(sroll,sname,sperc,sremark): with
open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc, "SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS-------------------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='') print(rec['SPERC'],'\t
',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :")) for
ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while
True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError: break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
def main():
while True:
print('\nYour Choices are: ') print('1.Insert Records')
print('2.Dispaly Records') print('3.Update Records')
print('0.Exit (Enter 0 to exit)') ch=int(input('Enter Your
Choice: ')) if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()
OUTPUT:
Your Choices are:
1.Insert Records 2.Dispaly
Records 3.Update Records 0.Exit
(Enter 0 to exit) Enter Your
Choice: 1
How many records you want to create :2
Enter Roll No: 1
Enter Name:
abinaya Enter
Percentage: 87
Enter Remark:
good Enter Roll
No: 2 Enter Name:
sanjana Enter
Percentage: 92
Enter Remark: excellent
Your Choices are:
1. Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to
exit) Enter Your
Choice: 2
-------DISPALY STUDENTS DETAILS--------
Roll No. Name Percetage Remarks
1 abinaya 87.0 good
2 sanjana 92.0 excellent
Your Choices
are: 1.Insert
Records
2.Dispaly
Records
3.Update Records
0.Exit (Enter 0 to
exit) Enter Your
Choice: 3
Enter a Rollno to be update: 2
Enter Name: sanjana
Enter Percentage: 91
Enter Remark: excellemt
Your Choices are:
1. Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to
exit) Enter Your
Choice: 2
-------DISPALY STUDENTS DETAILS--------
Roll No. Name Percetage Remarks
1 abinaya 87.0 good
2 sanjana 91.0 excellemt
Your Choices are:
1.Insert Records
2.Dispaly Records
3.Update Records
0.Exit (Enter 0 to exit)
Enter Your Choice: 0
RESULT:
Thus the python program to create and update the student details in
a binary file is done successfully and the output is verified.
13. Storing and retrieving student’s information using csv file
Aim: To store and retrieve student’s information using csv file.
ALGORITHM:
STEP 1:Import csv module
STEP 2:Assign an empty list to a variable stu STEP
3:Define a function write_csv_data() STEP 4:Open
the csv file with append mode STEP 5:Create the
writer object
STEP 6:Get the name and total marks from the user and assign it to a list STEP
7:Using writerow() write the data into the csv file
STEP 8: :Define a function read_csv_data() STEP
9:Open the file with read mode
STEP 10:Read the data using reader object STEP
11:Print the data
STEP 12:Call the function
STEP 13:Stop the program
PROGRAM:
import csv
stu = []
def write_csv_data():
with open('InputData.csv','w',newline='') as F: Write =
csv.writer(F)
ch = 'y'
while ch == 'y':
name = input('Enter the student name:')
totalmarks = int(input('Total marks:')) stu =
[name,totalmarks] Write.writerow(stu)
ch = input('Do you want to continue y/n: ') def
read_csv_data():
with open('InputData.csv','r') as F:
Reader = csv.reader(F)
for Data in Reader:
print(Data[0],int(Data[1]))
write_csv_data()
read_csv_data()
OUTPUT:
Enter the student name:aaa
Total marks:450
Do you want to continue y/n: y
Enter the student name:bbb
Total marks:340
Do you want to continue y/n: n aaa 450 bbb 34
Program 14: CSV FILE HANDLING
import csv
def copy_csv_data():
with open ("E://input data 03.csv") as f1:
with open("write data 01.csv","w",newline="") as f2:
read=csv.reader(f1) write=csv.writer(f2,delimiter="#")
for line in read:
write.writerows(line)
def display_copied_data():
with open("write data 01.csv")as f:
reader=csv.reader(f)
for data in reader:
print(data)
copy_csv_data()
display_copied_data()
output:
['h#a#p#p#y# #b#i#r#t#h#d#a#y# #t#o# #u# #m#y# #f#r#i#e#n#d# #h#o#w# #a#r#e# #u#
#a#r#e# #u# #f#i#n#e']
PROGRAM-15: STACK OPERATIONS
def isempty(stk):
if stk==[]:
return True
else:
return False def
push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk): return"UNDERFLOW"
else:
item=stk.pop()
print(item)
if len(stk)==0:
top=None
else:
top=len(stk)-1
def peek(stk):
if isempty(stk):
return "UNDERFLOW"
else:
top=len(stk)-1
return stk[top]
def display(stk): if
isempty(stk):
print('stack is empty!!') else:
top=len(stk)-1
print(stk[top],"<- TOP")
for a in range(top-1,-1,-1):
print(stk[a])
#main
stack=[]
top=None
print("stack operations:")
print("1.push")
print("2.pop")
print("3.peek")
print('4.display')
print('5.exit') while
True:
ch=int(input("ENTER YOUR CHOICE:")) if
ch==1:
item=int(input("ENTER THE ITEM:"))
push(stack,item) elif
ch==2:
item=pop(stack)
if item=="UNDERFLOW":
print("stack is empty!!")
elif ch==3:
item=peek(stack)
if item=="UNDERFLOW":
print("stack is empty!!")
else:
print("top most item is:",item) elif
ch==4:
display(stack) elif
ch==5:
break
else:print("INVALID CHOICE!!")
OUTPUT: stack
operations:
1.push
2.pop
3.peek
4.display
5.exit
ENTER YOUR CHOICE:1
ENTER THE ITEM:23 ENTER
YOUR CHOICE:1
ENTER THE ITEM:45
ENTER YOUR CHOICE:2 45
ENTER YOUR CHOICE:3 top most item is: 23
ENTER YOUR CHOICE:4 23 <-
TOP
PROGRAM 16
mysql> create database db;
Query OK, 1 row affected (0.04 sec)
mysql> use db;
Database changed
mysql> CREATE TABLE STUDENTS(EXAMNO INT PRIMARY KEY, NAME VARCHAR(20) NOT NULL,
CLASS VARCHAR(5), SEC VARCHAR (3), MARK INT CHECK(MARK<=500));
Query OK, 0 rows affected (0.13 sec)
mysql> desc students;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| EXAMNO | int | NO | PRI | NULL | |
| NAME | varchar(20) | NO | | NULL | |
| CLASS | varchar(5) | YES | | NULL | |
| SEC | varchar(3) | YES | | NULL | |
| MARK | int | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
mysql> INSERT INTO STUDENTS VALUES(1201,'PAVITHRAN','XII','A1',489);
Query OK, 1 row affected (0.03 sec)
mysql> INSERT INTO STUDENTS VALUES(1202,'BHARKAVI','XII','A1',485);
Query OK, 1 row affected (0.03 sec)
mysql> INSERT INTO STUDENTS VALUES(1203,'ESHWAR', 'XII', 'A2', 475);
Query OK, 1 row affected (0.03 sec)
mysql> SELECT * FROM STUDENTS;
+--------+-----------+-------+------+------+
| EXAMNO | NAME | CLASS | SEC | MARK |
+--------+-----------+-------+------+------+
| 1201 | PAVITHRAN | XII | A1 | 489 |
| 1202 | BHARKAVI | XII | A1 | 485 |
| 1203 | ESHWAR | XII | A2 | 475 |
+--------+-----------+-------+------+------+
mysql> SELECT * FROM STUDENTS WHERE SEC='A1';
+--------+-----------+-------+------+------+
| EXAMNO | NAME | CLASS | SEC | MARK |
+--------+-----------+-------+------+------+
| 1201 | PAVITHRAN | XII | A1 | 489 |
| 1202 | BHARKAVI | XII | A1 | 485 |
+--------+-----------+-------+------+------+
mysql> SELECT * FROM STUDENTS WHERE MARK IS NULL;
Empty set (0.00 sec)
mysql> SELECT * FROM STUDENTS WHERE MARK BETWEEN 400 AND 450;
Empty set (0.00 sec)
PROGRAM 17
mysql> SELECT NAME,MARK FROM STUDENTS WHERE MARK>400 AND MARK<487;
+----------+------+
| NAME | MARK |
+----------+------+
| BHARKAVI | 485 |
| ESHWAR | 475 |
+----------+------+
mysql> SELECT * FROM STUDENTS WHERE NAME LIKE 'P%' OR NAME LIKE 'B%';
+--------+-----------+-------+------+------+
| EXAMNO | NAME | CLASS | SEC | MARK |
+--------+-----------+-------+------+------+
| 1201 | PAVITHRAN | XII | A1 | 489 |
| 1202 | BHARKAVI | XII | A1 | 485 |
+--------+-----------+-------+------+------+
mysql> SELECT * FROM STUDENTS;
+--------+-----------+-------+------+------+
| EXAMNO | NAME | CLASS | SEC | MARK |
+--------+-----------+-------+------+------+
| 1201 | PAVITHRAN | XII | A1 | 489 |
| 1202 | BHARKAVI | XII | A1 | 485 |
| 1203 | ESHWAR | XII | A2 | 475 |
+--------+-----------+-------+------+------+
mysql> SELECT EXAMNO,NAME,CLASS,SEC,MARK+10 AS 'UPDATE MARKS'FROM STUDENTS;
+--------+-----------+-------+------+--------------+
| EXAMNO | NAME | CLASS | SEC | UPDATE MARKS |
+--------+-----------+-------+------+--------------+
| 1201 | PAVITHRAN | XII | A1 | 499 |
| 1202 | BHARKAVI | XII | A1 | 495 |
| 1203 | ESHWAR | XII | A2 | 485 |
+--------+-----------+-------+------+--------------+
mysql> SELECT * FROM STUDENTS WHERE NAME LIKE 'P%' OR NAME LIKE 'B%';
+--------+-----------+-------+------+------+
| EXAMNO | NAME | CLASS | SEC | MARK |
+--------+-----------+-------+------+------+
| 1201 | PAVITHRAN | XII | A1 | 489 |
| 1202 | BHARKAVI | XII | A1 | 485 |
+--------+-----------+-------+------+------+
mysql> SELECT NAME, SEC FROM STUDENTS WHERE NAME LIKE '%PRIYA';
Empty set (0.00 sec)
PROGRAM 18
mysql> ALTER TABLE STUDENTS MODIFY CITY VARCHAR(30);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE STUDENTS MODIFY NAME VARCHAR(40);
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> UPDATE STUDENTS SET SEC='A3' WHERE SEC IS NULL;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql> UPDATE STUDENTS SET CITY="BENGALURU" WHERE EXAMNO=1201;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> DESC STUDENTS;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| EXAMNO | int | NO | PRI | NULL | |
| NAME | varchar(40) | YES | | NULL | |
| CLASS | varchar(5) | YES | | NULL | |
| SEC | varchar(3) | YES | | NULL | |
| MARK | int | YES | | NULL | |
| CITY | varchar(30) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
mysql> SELECT * FROM STUDENTS;
+--------+-----------+-------+------+------+---------------+
| EXAMNO | NAME | CLASS | SEC | MARK | CITY |
+--------+-----------+-------+------+------+---------------+
| 1201 | PAVITHRAN | XII | A1 | 489 | BENGALURU |
| 1202 | BHARKAVI | XII | A1 | 485 | NOT MENTIONED |
| 1203 | ESHWAR | XII | A2 | 475 | NOT MENTIONED |
+--------+-----------+-------+------+------+---------------+
PROGRAM 19
CREATE TABLE TEACHER(NAME VARCHAR(30) PRIMARY KEY,AGE INT,DEPARTMENT
VARCHAR(30),DATEOFJOIN DATE,SALARY INT,SEX VARCHAR(1));
INSERT INTO TEACHER VALUES('JUGAL',34,'COMPUTER','1997/01/10',12000,'M');
1.SELECT * FROM TEACHER WHERE DEPARTMENT='HISTORY';
+-----------+------+------------+------------+--------+------+
| NAME | AGE | DEPARTMENT | DATEOFJOIN | SALARY | SEX |
+-----------+------+------------+------------+--------+------+
| SANGEETHA | 35 | HISTORY | 1999-07-01 | 40000 | F |
| SHARMILA | 31 | HISTORY | 1998-03-24 | 20000 | F |
| SHYAM | 50 | HISTORY | 1998-06-27 | 30000 | M |
+-----------+------+------------+------------+--------+------+
mysql> SELECT * FROM TEACHER WHERE DEPARTMENT='HINDI'AND SEX='F';
Empty set (0.00 sec)
mysql> SELECT * FROM TEACHER ORDER BY DATEOFJOIN;
+-----------+------+------------+------------+--------+------+
| NAME | AGE | DEPARTMENT | DATEOFJOIN | SALARY | SEX |
+-----------+------+------------+------------+--------+------+
| SANDEEP | 32 | MATHS | 1996-12-12 | 30000 | M |
| JUGAL | 34 | COMPUTER | 1997-01-10 | 12000 | M |
| SHIVOM | 44 | COMPUTER | 1997-02-25 | 21000 | M |
| RAKESH | 42 | MATHS | 1997-03-05 | 25000 | M |
| SHARMILA | 31 | HISTORY | 1998-03-24 | 20000 | F |
| SHYAM | 50 | HISTORY | 1998-06-27 | 30000 | M |
| SANGEETHA | 35 | HISTORY | 1999-07-01 | 40000 | F |
+-----------+------+------------+------------+--------+------+
mysql> SELECT MAX(AGE) FROM TEACHER WHERE SEX='F';
+----------+
| MAX(AGE) |
+----------+
| 35 |
+----------+
Program 21: PYTHON – SQL CONNECTIVITY (CREATE TABLE)
PREREQUISITE:
1. CREATE DATABASE: create database employee;
2. MAKE IT ACTIVE: use database
AIM:
To write a python program to create a table in MYSQL using interface with python and Mysql.
PROGRAM:
import mysql.connector as mc
con=mc.connect(host="localhost",user="root",password="avpcbse",database="employee")
if con.is_connected():
print("Connected successfully")
cur=con.cursor()
cur.execute("create table empl(id int,name varchar(20),department varchar(30), gender char(1),salary int)")
con.close()
RESULT:
Thus, the python program to create a table using interface with python and MYSQL has been executed
successfully.
Output:
Connected successfully
Program 22: PYTHON – SQL CONNECTIVITY (INSERT RECORD)
PREREQUISITE:
1. CREATE DATABASE: create database employee;
2. MAKE IT ACTIVE: use database
3. CREATE TABLE: create table empl(id int,name varchar(20),department
varchar(30), gender char(1),salary int)
AIM:
To write a python program to create a table in MYSQL using interface with python and Mysql.
PROGRAM:
import mysql.connector as mc
con=mc.connect(host="localhost",user="root",password="avpcbse",database="employee")
if con.is_connected():
print("Connected successfully")
cur=con.cursor()
Id=int(input("Enter the employee id:"))
name=input("Enter the name:")
dept=input("Enter the dept:")
gender=input("Enter the gender:")
salary=int(input("Enter the salary:"))
a="insert into empl values({},'{}','{}','{}',{})".format(Id,name,dept,gender,salary)
cur.execute(a)
con.commit()
print(“Data inserted successfully”)
con.close()
Output:
Connected successfully
Data inserted successfully
RESULT:
Thus, the python program to create a table using interface with python and MYSQL has been executed
successfully.
Prgm : 23 PYTHON – SQL CONNECTIVITY(Update RECORD)
PREREQUISITE:
1. CREATE DATABASE: create database employee;
2. MAKE IT ACTIVE: use database
3. CREATE TABLE: create table empl(id int,name varchar(20),department
varchar(30), gender char(1),salary int)
4. INSERT values: (i) INSERT INTO EMPL VALUES(101,’aaa’,’sales’,’f’,20000)
(ii) INSERT INTO EMPL VALUES(102, 'bbb', 'production', 'f',
25000)
(iii)INSERT INTO EMPL VALUES (103, 'ccc', 'production', 'm',
26000)
Aim:
To write a python program to update a record in the table using interface with python and Mysql.
Program:
import mysql.connector as mc
con=mc.connect(host="localhost",user="root",password="avpcbse",database="employee")
if con.is_connected():
print("Connected successfully")
cur=con.cursor()
cur.execute("update empl set name='santra' where Id=103")
con.commit()
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
con.close()
Output:
Connected successfully
(102, 'bbb', 'production', 'f', 25000)
(103, 'santra', 'production', 'm', 26000)
Prgm : 24 PYTHON – SQL CONNECTIVITY(SELECT RECORDS)
PREREQUISITE:
5. CREATE DATABASE: create database employee;
6. MAKE IT ACTIVE: use database
7. CREATE TABLE: create table empl(id int,name varchar(20),department
varchar(30), gender char(1),salary int)
8. INSERT values: (i) INSERT INTO EMPL VALUES(101,’aaa’,’sales’,’f’,20000)
(ii) INSERT INTO EMPL VALUES(102, 'bbb', 'production', 'f',
25000)
(iii)INSERT INTO EMPL VALUES (103, 'ccc', 'production', 'm',
26000)
Aim:
To write a python program to select records from the table using interface with python and Mysql.
Program:
import mysql.connector as mc
con=mc.connect(host="localhost",user="root",password="avpcbse",database="employee")
if con.is_connected():
print("Connected successfully")
cur=con.cursor()
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
con.close()
output:
Connected successfully
(101, 'aaa', 'sales', 'f', 20000)
(102, 'bbb', 'production', 'f', 25000)
(103, 'ccc', 'production', 'm', 26000)
Prgm : 25 PYTHON – SQL CONNECTIVITY(DELETE RECORDS)
1. CREATE DATABASE: create database employee;
2. MAKE IT ACTIVE: use database
3. CREATE TABLE: create table empl(id int,name varchar(20),department
varchar(30), gender char(1),salary int)
4. INSERT values: (i) INSERT INTO EMPL VALUES(101,’aaa’,’sales’,’f’,20000)
(ii) INSERT INTO EMPL VALUES(102, 'bbb', 'production', 'f',
25000)
(iii)INSERT INTO EMPL VALUES (103, 'ccc', 'production', 'm',
26000)
Aim:
To write a python program to delete a record from the table using interface with python and Mysql.
PROGRAM:
import mysql.connector as mc
con=mc.connect(host="localhost",user="root",password="avpcbse",database="employee")
if con.is_connected():
print("Connected successfully")
cur=con.cursor()
cur.execute("delete from empl where Id=101")
con.commit()
print(“Data deleted successfully”)
con.close()
output:
Connected successfully
Data deleted successfully