1.
Factorial using Iteration
Aim:
To write a python program to find Factorial of a given number using iteration methods.
Program :
num = int (input ("Enter any number :"))
fact = 1
n = num
while num > 0:
fact = fact * num
num -= 1
print (" Factorial of ",n, " is: ", fact)
Result:
Thus the program has been executed successfully for finding the factorial of given number using
iteration and output was verified.
Output:
Enter any number :5
Factorial of 5 is: 120
2. Prime number or Not
Aim :
To write a python program to check whether a given number is prime or Not.
Program:
num = int (input ("Enter any number: "))
if num >1 :
for i in range(2,num):
if (num%i)==0:
print (num,"Not a prime number")
break
else :
print (num, "is a prime number")
elif num == 0 or 1 :
print (num, "is neither prime NOR composite number")
else :
print (num, "is NOT a prime nember,it is a composite")
Result:
Thus the program has been executed successfully for finding a number is prime or not and the
output was verified.
Output:
Enter any number: 21
21 Not a prime number
Enter any number: 1
1 is neither prime NOR composite number
Enter any number: 17
17 is a prime number
3. Fibonacci Series using Iteration
Aim:
To write a python program to calculate the fibonacci series for given number using iteration.
Program:
def fibo(num):
a=0
b=1
fib = [ a, b]
for i in range (3, num + 1) :
c=a+b
fib.append (c)
a=b
b=c
return fib
num = int (input ("How many terms?"))
print("Fibonacci series:", fibo(num))
Result :
Thus the program has been executed successfully for finding the Fibonacci series and its N th term
using iteration and the output was verified.
Output:
How many terms?10
Fibonacci series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
4. Simple Interest calculation
Aim :
To write a python program to calculate the simple Interest [SI= PRT/100] using user defined
function by passing p, r, t as argument.
Program:
def simple_interest(P, R, T):
print("The Principal is ",P)
print("The time period is", T)
print("The rate of interest is ",R)
return (P * R * T) / 100
P = float(input('Enter principal amount: '))
R = float(input('Enter the interest rate: '))
T = float(input('Enter time: '))
SI = simple_interest(P, R, T)
print("SI is:",SI)
Result:
Thus the program has been executed successfully for finding the simple Interest and output was
verified.
Output:
Enter principal amount: 10000
Enter the interest rate: 5
Enter time: 3
The Principal is 10000.0
The time period is 3.0
The rate of interest is 5.0
SI is: 1500.0
5. Leap year or not
Aim :
To write a python program to check whether the given year is leap year or not.
Program :
def leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
year = int(input("Enter a year: "))
leap_year(year)
Result:
Thus the program has been executed successfully to find a given year is a
Leap year or not and output was verified.
Output:
Enter a year: 2025
2025 is not a leap year
Enter a year: 1996
1996 is a leap year
6. Temperature conversation
Aim:
To write a python program to convert Celsius to Fahrenheit and Fahrenheit to Celsius using user
defined function [using f = (9/5) *C+ 32].
Program:
def Celsius_to_Fahrenheit (C) :
f = (9/5) * C + 32
return f
def Farenheit_to_Celsius (f) :
C = (5/9) * (f -32)
return C
if __name__=="__main__":
C = float (input ("Enter Celsius value :"))
print (C, "degree celsius is equal to : " ,Celsius_to_Fahrenheit (C), "Fahrenheit")
f = float (input ("enter Fahrenheit value: "))
print (f, "Fahrenheit is equal to:" ,Farenheit_to_Celsius(f), "degree Celsius")
Result:
Thus the program has been executed successfully for conversion of centigrade to Fahrenheit and
vice- Versa and output was verified.
Output:
Enter Celsius value :30
30.0 degree celsius is equal to : 86.0 Fahrenheit
enter Fahrenheit value: 86
86.0 Fahrenheit is equal to: 30.0 degree Celsius
7. Simple Arithmetic Calculation
Aim :
To write a python program to make a simple Arithmetic calculator.
Program:
def add (x, y):
return x+y
def subtract (x, y) :
return x-y
def multiply (x, y):
return x*y
def divide (x, y) :
return x/y
def floor_div (x, y):
return x//y
def mod_div (x, y):
return x%y
print ("Select operation")
print (" 1. Add")
print ("2. Subtract")
print ("3. Multiply")
print ( "4. Divide ")
print ("5. Floor Division")
print ("6. Modulus Division")
choice = input ("Enter choice (1/2/3/4/5/6) :")
while choice < '7' :
num1= int (input ("Enter first number:"))
num2= int (input ("enter second number: "))
if choice == '1':
print (num1, "+",num2, "=" ,add(num1, num2))
elif choice =='2':
print (num1, "-",num2, "=" ,subtract(num1, num2))
elif choice =='3':
print (num1, "*",num2, "=" ,multiply(num1, num2))
elif choice == '4' :
print (num1, "/",num2, "=" ,divide(num1, num2))
elif choice == '5' :
print (num1, "//",num2, "=" ,floor_div(num1, num2))
elif choice == '6':
print (num1, "%",num2, "=" ,mod_div(num1, num2))
choice = input ("Enter choice (1/2/3/4/5/6) : ")
print ("exited")
Result :
Thus the program has been executed successfully for designing a simple Arithmetic
Calculator and output was verified.
Output:
Select operation
1. Add
2. Subtract
3. Multiply
4. Divide
5. Floor Division
6. Modulus Division
Enter choice (1/2/3/4/5/6) :1
Enter first number:45
enter second number: 25
45 + 25 = 70
Enter choice (1/2/3/4/5/6) : 2
Enter first number:4
enter second number: 2
4-2=2
Enter choice (1/2/3/4/5/6) : 3
Enter first number:41
enter second number: 2
41 * 2 = 82
Enter choice (1/2/3/4/5/6) : 4
Enter first number:48
enter second number: 4
48 / 4 = 12.0
Enter choice (1/2/3/4/5/6) : 5
Enter first number:55
enter second number: 11
55 // 11 = 5
Enter choice (1/2/3/4/5/6) : 6
Enter first number:56
enter second number: 2
56 % 2 = 0
Enter choice (1/2/3/4/5/6) : 8
exited
8. Search A word
Aim :
To write a python program to search any word and to find the number of оссurrence in a given
string sentence.
Program:
def countword (str1, word):
S = str1. split ()
count = 0
for w in S:
if w == word:
count +=1
return count
str1= input ("Enter any sentence: ")
word = input ("Enter word to search in sentence:")
count = countword (str1, word)
if count == 0:
print ("sorry!", word, "not present")
else :
print (word, "occurs", count, "times")
Result:
Thus the program has been executed successfully for searching word in given sentence and output
was verified.
Output-1:
Enter any sentence: Ahmedabad Airport Shut For Operations Temporarily After Air India Crash
Enter word to search in sentence: Temporarily
Temporarily occurs 1 times
Output-2:
Enter any sentence: Ahmedabad Airport Shut For Operations Temporarily After Air India Crash
Enter word to search in sentence: Shot
sorry! Shot not present
9. Display file Content
Aim :
To write a python program to read and display file content line by line and each word separated by
"#".Program:
Program:
fh = open (r" linebyline . txt","r")
line = " "
while line :
line = fh.readline ()
word=line.split ( )
print ("#". join (word))
fh.close ( )
Result:
Thus the program has been executed successfully for separating each word in the file by the symbol
‘#’ and output was verified.
Output:
Input File:
A computer is a programmable device that stores, retrieves, and processes data. The term was later given to
mechanical devices as they began replacing human computers.
Output:
A #computer #is# a #programmable #device# that #stores#retrieves# and #processes #data# The# term
#was# later# given #to# mechanical# devices #as# they# began #replacing# human #computers
10. Counting consonants and vowels in a string
Aim :
To write a python program to read a text file and display the number of vowels/
consonants / uppercase / lowercase / Digits/ other than letters and digits in the text file.
Program:
filein = open ('line by line.txt',"r")
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print ( "* * * Input file *** ")
print (line)
for ch in line:
if ch.isupper( ):
count_up+=1
if ch.islower():
count_low+=1
if ch=="aeiou" or "AEIOU":
count_vow+=1
if ch.isalpha() :
count_con+=1
if ch.isdigit():
count_digit+=1
if ch.isalnum()!= 'True' and ch!=''and ch!='\n':
count_other+=1
print ( "*** The count ***" )
print ("vowels :",count_vow)
print ("consonants", count_con)
print ("upper case:",count_up)
print ("Lower case: ", count_low)
print ("Digits:", count_digit)
print ("Other than letter and digit: ",count_other)
filein.close()
Result
Thus the program to read text file and display the numbers of vowels/ consonants/
upper case /lowercase / Digits/ other than digits and letter in file has executed and output is
verified.
Output:
* * * Input file ***
Let's modify the previous program. This program uses "end" to skip printing an automatic newline.
The "try-except" block is used for exception handling.
*** The count ***
vowels : 150
consonants 121
upper case: 3
Lower case: 118
Digits: 0
Other than letter and digit: 150
11. Copying A file
Aim:
To read the content from a file line by line and write it to another file except for those line contains
letter "a" in it.
Program:
def lines(file,cfile):
with open(file, 'r') as infile, open(cfile, 'w') as outfile:
for line in infile:
if 'a' not in line:
outfile.write(line)
filename = 'myfile1.txt'
copy_filename = 'file2.txt'
lines(filename, copy_filename)
Result:
Thus the program has been executed successfully for coping a file to another
file except lines has letter 'a' and output was verified.
Output:
Input :
Copy- Notepad
File Edit Format View Help
Even to our homes they come with bold:
Prostrating to both young and old,
Promising us heaven on earth,
But all this they'll soon forget
newfile - Notepad
File Edit Format View Help
Even to our home they come with bold
12. Creation of a Binary File
Aim:
To write a python program to create binary file to store Roll no and Name search and display name
if Roll no found otherwise "Roll no Not found".
Program:
import pickle
def create () :
f = open ("Student.dat", "wb")
opt = 'y'
while opt.lower ( )=='y':
rollno=int (input ("Enter roll number:"))
name = input ("Enter a name: ")
L = [rollno, name]
pickle.dump(L,f)
opt = input ("Do you want to add another student details? Press (y/n):")
f. close ()
def search () :
f = open ("student.dat", "rb")
rollno =int(input ("Enter the roll no to be searched : "))
found = 0
try :
while True :
s= pickle.load (f)
if s[0]==rollno:
print ("searched roll no is found and details are: ",s)
found=1
break
except EOFError :
f.close ()
if found==0:
print ("The searched record is not found")
create ()
search()
Result:
Thus the program has been executed successfully for searching the student name in binary file when
roll no exist and output was verified.
Output:
Enter roll number:1
Enter a name: Rakshu
Do you want to add another student details? Press (y/n):y
Enter roll number:2
Enter a name: Brindha
Do you want to add another student details? Press (y/n):n
Enter the roll no to be searched : 2
searched roll no is found and details are: [2, 'Brindha']
13. Updating a Binary file
Aim:
To create binary file to store Roll no, Name and Marks are update the Marks of
entered Roll no.
Program:
import pickle
def create():
f = open("Mark.dat", "wb")
opt = 'y'
while opt.lower() == 'y':
rollno = int(input("Enter roll number: "))
name = input("Enter name: ")
mark = float(input("Enter the Mark: "))
L = [rollno, name, mark]
pickle.dump(L, f)
opt = input("Do you want to add student details? (y/n): ")
f.close()
def update():
f = open("Mark.dat", "rb+")
rollno = int(input("Enter the roll no to update: "))
found = 0
try:
while True:
pos = f.tell()
s = pickle.load(f)
if s[0] == rollno:
print("Searched Rollno found. Details:", s)
s[2] = float(input("Enter the new mark: "))
f.seek(pos)
pickle.dump(s, f)
found = 1
print("Mark updated successfully. New details:", s)
break
except EOFError:
f.close()
if found == 0:
print("The searched record was not found.")
create()
update()
Result:
Thus the program has executed successfully for searching the student name and update their marks
in binary file when roll number is exist and output was verified.
Output:
Enter roll number: 1
Enter name: Suganya
Enter the Mark: 87
Do you want to add student details? (y/n): y
Enter roll number: 2
Enter name: Lakshitha
Enter the Mark: 53
Do you want to add student details? (y/n): n
Enter the roll no to update: 2
Searched Rollno found. Details: [2, 'Lakshitha', 53.0]
Enter the new mark: 68
Mark updated successfully. New details: [2, 'Lakshitha', 68.0]
14. Generation Random Number
Aim:
To write a random number generator that generates random numbers between
1 and 6 (simulates a dice).
Program:
import random
while True:
print("=" * 55)
print("******** Rolling The Dice *********")
print("=" * 55)
num = random.randint(1, 6)
if num == 6:
print("Hey, you got", num, "congratulations!!!")
elif num == 1:
print("Well tried... But you got", num)
else:
print("You got", num)
ch = input("Roll again? (Y/N) ")
if ch in "Nn":
break
print("Thanks for playing!!!!!")
Result:
Thus the program has been executed successfully for generating the random
numbers between 1 and 6 using a dice and output was verified.
Output:
=======================================================
******** Rolling The Dice *********
=======================================================
You got 4
Roll again? (Y/N) y
=======================================================
******** Rolling The Dice *********
=======================================================
Well tried... But you got 1
Roll again? (Y/N) y
=======================================================
******** Rolling The Dice *********
=======================================================
Hey, you got 6 congratulations!!!
Roll again? (Y/N) n
Thanks for playing!!!!!
15. CSV Login username and password
Aim:
To write a python programme to create a CSV file by entering user- id and password, read and
search the password for given user id.
Program:
import csv
def write():
with open("Details.csv", "w", newline='') as f:
wo = csv.writer(f)
wo.writerow(["User ID", "Password"])
while True:
u_id = input("Enter user-id: ")
pswd = input("Enter password: ")
data = [u_id, pswd]
wo.writerow(data)
ch = input("Do you want to enter more? (Y/N): ")
if ch.upper() == "N":
break
def read():
with open("Details.csv", "r", newline='') as f:
ro = csv.reader(f)
for i in ro:
print(i)
def search():
with open("Details.csv", "r", newline='') as f:
u = input("Enter user-id to search: ")
ro = csv.reader(f)
found = False
for i in ro:
if i[0] == u:
print("Password:", i[1])
found = True
break
if not found:
print("Not found")
write()
read()
search()
Result:
Thus the above program to create a CSV files by entering user-id and password to read and search
the password was successfully executed.
Output:
Enter user-id: Pradeep
Enter password: 1234
Do you want to enter more? (Y/N): y
Enter user-id: Madhu
Enter password: 5412
Do you want to enter more? (Y/N): y
Enter user-id: Nihan
Enter password: 7481
Do you want to enter more? (Y/N): n
['User ID', 'Password']
['Pradeep', '1234']
['Madhu', '5412']
['Nihan', '7481']
Enter user-id to search: Madhu
Password: 5412
16. Implementation a stack using List
Aim:
To write a python program to implement stack using list.
Program:
def Push():
Doc_ID = int(input("Enter the Doctor ID: "))
Doc_Name = input("Enter the Name of the Doctor: ")
Mob = int(input("Enter the Mobile Number of the Doctor: "))
Special = input("Enter the Specialization: ")
Stack.append([Doc_ID, Doc_Name, Mob, Special])
def Pop():
if Stack == []:
print("Stack is empty")
else:
print("The deleted doctor detail is", Stack.pop())
def Peek():
if Stack == []:
print("Stack is empty")
else:
top = len(Stack)-1
print("The top of the stack is", Stack[top])
def Disp():
if Stack == []:
print("Stack is empty")
else:
top = len(Stack)-1
for i in range(top, -1, -1):
print(Stack[i])
Stack = []
ch = 'y'
print("Performing Stack Operations Using List")
while ch == 'y' or ch == 'Y':
print("\n1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. DISPLAY")
opt = int(input("Enter your choice: "))
if opt == 1:
Push()
elif opt == 2:
Pop()
elif opt == 3:
Peek()
elif opt == 4:
Disp()
else:
print("Invalid Choice, Try Again!!!")
ch = input("\nDo you want to Perform another operation? (y/n): ")
Result:
Thus the above program to implement a stack using list has been executed successfully and output
was verified.
Output:
Performing Stack Operations Using List
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 1
Enter the Doctor ID: 100
Enter the Name of the Doctor: bean
Enter the Mobile Number of the Doctor: 4756
Enter the Specialization: cardio
Do you want to Perform another operation? (y/n): y
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 4
[100, 'bean', 4756, 'cardio']
Do you want to Perform another operation? (y/n): y
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 1
Enter the Doctor ID: 200
Enter the Name of the Doctor: ninja
Enter the Mobile Number of the Doctor: 7854
Enter the Specialization: dentist
Do you want to Perform another operation? (y/n): y
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 3
The top of the stack is [200, 'ninja', 7854, 'dentist']
Do you want to Perform another operation? (y/n): y
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 4
[200, 'ninja', 7854, 'dentist']
[100, 'bean', 4756, 'cardio']
Do you want to Perform another operation? (y/n): y
1. PUSH
2. POP
3. PEEK
4. DISPLAY
Enter your choice: 2
The deleted doctor detail is [200, 'ninja', 7854, 'dentist']
Do you want to Perform another operation? (y/n): n
17. SQL commands Exercise – 1
Aim:
To write Queries for the following Questions based on the given table STUDENT.
Note: Write this table in the Output side page no:1
Command:
a) Write a Query to create a New Database in the name of 'Students'.
mysql > CREATE DATABASE STUDENTS;
b) Write a Query to open database "students"
mysql > USE STUDENTS;
c) Write a Query to create to above table called : student
mysql > CREATE TABLE student ( Rollno INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Gen
der CHAR(1), Age INT, Dept VARCHAR(50), DOA DATE, Fees INT);
d) Write a query to list all the existing database names.
mysql > SHOW DATABASES;
Note: Write this table in the Output side page , opposite to writing the above query
Database
Information_schema
Employee
mysql
sys
students
Tables-in-students
students
e) Write a Query to List all the tables that exists in current database.
mysql > SHOW Tables ;
f) Write a Query to insert all the rows of the above table into STUDENT table.
mysql > INSERT INTO student (Rollno, Name, Gender, Age, Dept, DOA, Fees) VALUES
(1, 'Arun', 'M', 24, 'COMPUTER', '1997-01-10', 120),
(2, 'Ankit', 'M', 21, 'HISTORY', '1998-03-24', 200),
(3, 'Anu', 'F', 20, 'HINDI', '1996-12-12', 300),
(4, 'Bala', 'M', 19, NULL, '1999-07-01', 400),
(5, 'Charan', 'M', 18, 'HINDI', '1997-09-05', 250),
(6, 'Deepa', 'F', 19, 'HISTORY', '1997-06-27', 300),
(7, 'Dinesh', 'M', 22, 'COMPUTER', '1997-02-25', 210),
(8, 'Usha', 'F', 23, NULL, '1997-07-31', 200);
h) Write a Query to display Rollno, Name, and Department of the student's from STUDENT table for:
mysql > SELECT Rollno, Name, Dept FROM student;
Note: Write this table in the Output side page , opposite to writing the above query
Rollno Name Dept
1 Arun COMPUTER
2 Ankit HISTORY
3 Anu HINDI
4 Bala NULL
5 Charan HINDI
6 Deepa HISTORY
7 Dinesh COMPUTER
8 Usha NULL
Result:
Thus the above commands has been executed successfully.
18. SQL Commands Exercise - 2
Aim:
To write Queries for the following question based on the given table student .
Command:
a) Write a Query to select Distinct Department from: STUDENT table.
mysql > SELECT DISTINCT Dept FROM student WHERE Dept IS NOT NULL;
Note: write this table opposite to this query in Output side.
Dept
COMPUTER
HISTORY
HINDI
b) To show all the information about students of computer department.
mysql > SELECT * FROM student WHERE Dept = 'COMPUTER';
Note: write this table opposite to this query in Output side.
c) Write a Query to list name of students in Hindi Department, (only females students
in the Department).
mysql > SELECT Name FROM student WHERE Dept = 'HINDI' AND Gender = 'F';
Note: write this table opposite to this query in Output side.
d)Write a Query to list name of the students whose age are between 18 to 20.
mysql > SELECT Name, Age FROM student WHERE Age BETWEEN 18 AND 20
ORDER BY Age;
e) Write a Query to display the name of the student's whose name is ending with 'A'.
mysql > SELECT Name FROM student WHERE Name LIKE '%a';
f) Write a Query to display the name of students whose name have second alphabet 'i' in their names:
mysql > SELECT Name FROM student WHERE Name LIKE '_i%';
Result:
Thus the above command has been executed successfully.
19. SQL Commands Exercise – 3
Aim:
To write Queries for the following questions based on the given table student.
Command :
a) write a Query to change the fees of students to 20000 whose Rollno is 1, if the existing fees is less
than 130.
mysql > UPDATE student SET Fees = 20000 WHERE Rollno = 1 AND Fees < 130;
b) write a Query to add the new column Area of type Varchar in the table student.
mysql > ALTER TABLE student ADD COLUMN Area VARCHAR(50);
c) Write a Query to Display Name of all the students whose Dept is NOT NULL.
mysql > SELECT Name FROM student WHERE Dept IS NOT NULL;
d) Write a Query to delete the details of Roll number is 4.
mysql > DELETE FROM student WHERE Rollno = 4;
e) Write a Query to delete column Area from the table student.
mysql > ALTER TABLE student DROP COLUMN Area;
f) Write a Query to delete table from Database.
mysql > DROP TABLE student;
Result:
Thus the above command has been executed successfully.
20. SQL commands Exercise – 4
Aim:
To write Queries for the following Questions based on the given table student.
Command :
a) Write a Query to arrange the record based on admission-no (DOA) in descending.
order.
mysql > SELECT * FROM student ORDER BY DOA DESC;
b) Write a Query to display the department and number of students in each department, arrange the
details based on number of students in each department in increasing order.
mysql > SELECT Dept , COUNT(DEPT) FROM student GROUP BY Dept ORDER BY COUNT(Dept);
c) Write a Query to display the details of students in a department is more than 1.
mysql > SELECT Dept, count (dept) FROM STUDENT Group By dept Having count (dept) > 1;
d) Write a Quary to find the total fees for each department.
mysql > SELECT dept, sum (fees) FROM STUDENTS GROUP BY Dept;
e) Write a Query to find the average fees in each department.
mysql > SELECT Dept, Avg (fees) FROM STUDENT GROUP BY Dept;
Result:
Thus the above command has been executed successfully.
21. SQL commands exercise – 5
Aim:
To write Queries for the following Questions based on the given table:
create a Doctors and salary table and INSERT data. Implement the following SQL
commands on the Doctors and salary.
Note:- OUTPUT side:
TABLE:- DOCTOR
ID NAME DEPT SEX EXPERIENCE
101 JOHN ENT M 12
104 SMITH ORTHOPEDIC M 5
107 GEORGE CARDIOLOGY M 10
114 LARA SKIN F 3
109 KAILA MEDICINE F 9
105 JOHNSON ORTHOPEDIC M 15
117 LUCY ENT F 3
111 MORPHY MEDICINE M 15
130 BILL ORTHOPEDIC F 12
TABLE:- SALARY
ID BASIC ALLOWANCE CONSULTATION
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
103 21700 2600 300
Command:
a) Display Name of all doctors who are in "Medicine" having more than 10 years
experience from the table DOCTOR.
mysql > SELECT NAME DOCTOR WHERE DEPT = "Medicine" AND Experience > 10;
NAME
MORPHY
b) Display the average salary of all the doctors working IN "ENT" department using the
tables DOCTOR and Salary (Salary = Basic + Allowance)
mysql > SELECT AVG(s.BASIC + s.ALLOWANCE) AS AVERAGE_SALARY
FROM DOCTOR d JOIN SALARY s ON d.ID = s.ID WHERE d.DEPT = 'ENT';
AVERAGE_SALARY
13000.0000
C) Display minimum Allowance of female doctors.
mysql > SELECT min (Allowance) FROM SALARY DOCTOR WHERE
SEX = ‘F’ AND Doctor . ID= Salary . ID;
MINIMUM_ALLOWANCE
1700
d) Display Doctor ID, Name from the table Doctor and Basic, Allowance from the
table salary with their corresponding matching ID.
mysql> SELECT DOCTOR . ID, Name, Basic Allowance FROM Doctor, Salary
WHERE Doctor. 18= Salary. ID;
e) To Display distinct department from the table Doctor.
mysql > SELECT DISTINCT (Dept) FROM DOCTOR;
Result :
Thus the above command has been executed successfully.
22. Program to fetchall the records from student table.
Aim:
To write a python program to fetch all the records from the student table.
Program:
import mysql.connector as sqltor
con = sqltor.connect(host="localhost", user="root", password="root",database="students")
if con.is_connected() == False:
print('Error connecting to database')
else:
cursor = con.cursor()
cursor.execute("SELECT * FROM student")
data = cursor.fetchall()
count = cursor.rowcount
print("No of Rows:", count)
for row in data:
print(row)
con.close()
Result:
Thus the program to integrate with MySQL to fetch all record from a table was
executed successfully and output was verified.
OUTPUT:
No. of Rows: 6
(1, 101, 'Arun', 'M', 24, 'Computer', datetime.date(2007, 1, 10), 20000)
(2, 112, 'Deep', 'F', 19, 'History', datetime.date(1997, 6, 27), 300)
(3, 110, 'Eniya', 'F', 18, 'Hindi', datetime.date(2005, 5, 15), 10000)
(5, 125, 'Krithiv', 'M', 19, 'Hindi', datetime.date(2004, 9, 25), 7500)
(6, 137, 'Jany', 'M', 25, 'None', datetime.date(1997, 2, 24), 8500)
(7, 103, 'Liga', 'F', 19, 'Computer', datetime.date(2004, 6, 27), 300)
23.Program to fetch Records which satisfies to given condition.
Aim:
To write a python program to fetch all the records from the student Table which satisfies the
given condition.
Program:
import mysql.connector as sqltor
con = sqltor.connect(host="localhost",user="root",password="root",database="students")
if not con.is_connected():
print('Error: Could not connect to database')
else:
cursor = con.cursor()
query = "SELECT * FROM student WHERE fee >= %s"
cursor.execute(query, (5000,))
data = cursor.fetchall()
count = cursor.rowcount
print("No. of Rows:", len(data))
for row in data:
print(row)
con.close()
Result:
Thus the python program to integrate with MySQL to fetch record from a table
was executed successfully and output was Verified.
Output:
No. of Rows: 4
(1, 101, 'Arun', 'M', 24, 'Computer', datetime.date(2007, 1, 10), 20000)
(3, 110, 'Eniya', 'F', 18, 'Hindi', datetime.date(2005, 5, 15), 10000)
(5, 125, 'Krithiv', 'M', 19, 'Hindi', datetime.date(2004, 9, 25), 7500)
(6, 137, 'Jany', 'M', 25, 'None', datetime.date(1997, 2, 24), 8500)
24. Program to Insert New Record into Table
Aim:
To write a python program to insert new record into student table.
Program:
import mysql.connector as sqltor
con= sqltor. connect (host="localhost",user="root",password="root",database="students")
if con.is_connected = = False:
print (“error”)
cur = con. cursor()
Query = "Insert into Student (Roll_NO, Admission_No,Name , gender, Age, Dept, Fees) values
({}, {}, {}, {}, {}, {}, { }) " format (8, 119, 'RIYA','F',29,'BIOLOGY',50000);"
cur.execute (Query)
cur.commit ( )
print ("Record Inserted")
cur.execute ("select * FROM student ")
print ("Table after insertion")
data = cur . fetchall()
for row in data:
print (row)
con . close ()
Result :
Thus the python program to integrate with MySQL to insert new record into table was
executed successfully and output was verified.
Output:
Record Inserted
Table after insertion
(1, 101, "Arun", "M", 24, "Computer", datetime.date(2007, 1, 10), 20000)
(2, 112, "Deepa", "F", 19, "History", datetime.date(2005, 5, 15), 10000)
(3, 110, "Reniya", "F", 18, "Hindi", datetime.date(2005, 6, 27), 300)
(5, 125, "Krithiv", "M", 29, "Hindi", datetime.date(2004, 9, 25), 7500)
(6, 137, "Jony", "M", 25, None, datetime.date(1997, 2, 24), 8500)
(7, 103, "Liya", "F", 19, "Computer", datetime.date(2004, 6, 24), 300)
(8, 113, "Riya", "F", 29, "Biology", None, 5000)
25. Program to update Record in a Table.
Aim:
To write a python program to update record in student table.
Program:
import mysql.connector as sqltor
con= sqltor. connect (host="localhost",user="root",password="root",database="students")
if con.is_connected = = False:
print (“error”)
cur = con. cursor()
query = "UPDATE student SET DOB = %s WHERE id = %s"
cur.execute(query)
con.commit()
print("Record Updated")
cur.execute("SELECT name, dob, dept FROM student")
print("Table after update:")
data = cur.fetchall()
for row in data:
print(row)
con.close()
Result :
Thus the python program to integrate with MySQL to insert new record into table was
executed successfully and output was verified.
Output:
Record Updated
Table after update:
('Arun', datetime.date(2000, 1, 1), 'Computer')
('Deepa', datetime.date(2005, 5, 15), 'History')
('Eniya', datetime.date(2005, 6, 27), 'Hindi')
('Krithiv', datetime.date(2004, 9, 25), 'Hindi')
('Jony', datetime.date(1997, 2, 24), None)
('Liya', datetime.date(2004, 6, 24), 'Computer')
('Riya', None, 'Biology')