Program:1
def Factorial(num):
result = 1
for i in range(2, num + 1):
result *= i
return result
def Power(base, exp):
result = 1
for _ in range(exp):
result *= base
return result
def compute_series_sum(x, n):
sum_series = 0
exponent = 1
factorial_denominator = 2
sign = 1 # Alternates between +1 and -1
for _ in range(n):
numerator = Power(x, exponent)
denominator = Factorial(factorial_denominator)
term = sign * (numerator / denominator)
sum_series += term
exponent += 2
factorial_denominator += 2
sign *= -1
return sum_series
x = int(input("Enter the value of x: "))
n = int(input("Enter the number of terms (n): "))
series_sum = compute_series_sum(x, n)
print(f"The sum of the series up to {n} terms is: {series_sum}")
Program:2
import statistics
def calculate_statistics(numbers):
mean = statistics.mean(numbers)
median = statistics.median(numbers)
mode = statistics.mode(numbers) # Works if only one mode
return mean, median, mode
def main():
input_str = input("Enter a list of integers separated by space: ")
numbers_str = input_str.split() # Split into list of strings
numbers = [] # Empty list to hold integers
for num in numbers_str:
numbers.append(int(num)) # Convert each to integer and add to list
mean, median, mode = calculate_statistics(numbers)
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
main()
Output:
Program:3
#Program 3 Menu driven-Numeric
def fact(n):
f=1
for i in range(1,n+1):
f*=i
return f
def fibo(n):
f1,f2,f3=-1,1,0
for i in range(n):
f3=f1+f2
print(f3,end=",")
f1=f2
f2=f3
while True:
print(''' ********** MENU DRIVEN CODE - FACTORIAL/ FIBONACCI NUMBER **********
1. FACTORIAL OF A NUMBER
2.GENERATE FIBONACCI SERIES UPTO 'N' NUMBERS
3.EXIT ''')
ch=int(input("Enter your choice"))
if ch==1:
num=int(input("Enter the number to find its factorial:"))
print("The factorial of ", num,"is",fact(num))
elif ch==2:
num1=int(input("Enter the number to generate fibonacci series:"))
fibo(num1)
elif ch==3:
break
else:
print("Invalid choice:")
Output:
Program 4:
#program 3 MENU DRIVEN CODE –LIST/STRING
def rev_str(s):
s1=''
if len(s)==0:
return s
else:
for i in range(len(s)-1,-1,-1):
s1+=s[i]
return s1
def binary_search(alist,num):
start=0
end=len(alist)-1
mid=(start+end)//2
while start<=end:
if num==alist[mid]:
print(num,"is found at",mid+1,"position")
break
if num>=alist[mid]:
start=mid+1
mid=(start+end)//2
else:
end=mid+1
mid=(start+end)//2
else:
print(num,"is not present in the given list")
print(''' MENU
1.Binary search in a list of integers
2.Reversing a string
3.Exit''')
while True:
ch=int(input("Enter your choice:"))
if ch==1:
alist=eval(input("Enter numbers for the list in ascending order:"))
n=int(input("Enter the number to be searched:"))
binary_search(alist,n)
elif ch==2:
str=input("Enter a string:")
print("Original string",str)
print("Reversed string",rev_str(str))
elif ch==3:
break
else:
print("Invalid choice")
Output:
Program 5
#program 5-Largest ,Second largest and Prime number from random generation
import random
def prime(l,n):
l1=[]
for i in l:
if i==0 or i==1 :
print(i,"Neither prime or consonent")
else:
isprime=True
for j in range(2,int(i**0.5)+1):
if i%j==0:
isprime=False
break
if isprime:
l1.append(i)
if not l1:
print("No Prime number in the list")
else:
print("The prime numbers are:",list(set(l1)))
#first and second largest element
def Max_num(l,n):
l=list(set(l))
l.sort()
print("The first largest element in the list is:",l[-1])
print("The second largest element in the list is :",l[-2])
#Generating random number
def Generate():
n=int(input("Enter no of terms:"))
x=int(input("Enter the x value:"))
y=int(input("Enter the y value:"))
l=[]
for i in range(n):
a=random.randint(x,y)
l.append(a)
print(l)
prime(l,n)
Max_num(l,n)
#main
Generate()
Output:
Program: 6
# Function to calculate BMI and return category
def compute_bmi(person):
height = person[0]
weight = person[1]
bmi = weight / (height ** 2)
if bmi >= 30.0:
return "Obese"
elif bmi >= 25.0:
return "Overweight"
elif bmi >= 18.5:
return "Normal"
else:
return "Underweight"
# Main part
# Reading height and weight into a nested tuple
n = int(input("Enter number of persons: "))
people = ()
for i in range(n):
h = float(input(f"Enter height (in meters) for person {i+1}: "))
w = float(input(f"Enter weight (in kg) for person {i+1}: "))
people += ((h, w),)
# Calling the function for each person and displaying result
print("\nBMI Results:")
for i in range(n):
category = compute_bmi(people[i])
print(f"Person {i+1} → Height: {people[i][0]} m, Weight: {people[i][1]} kg → Category: {category}")
Output:
Program7
def add(d):
name=input("Enter the name:")
ph=int(input("Enter the phone number:"))
d[ph]=name
def delete(d):
dph=int(input("Enter the phone number to be removed:"))
if dph in d:
d.pop(dph)
else:
print("Phone number not present ")
def modify(d,mph):
if mph in d:
n=input("Enter a new name:")
d[mph]=n
else:
print("Phone number not present")
def show(d):
print("Current status of the dictionary:")
print(d)
print("MENU \n 1.ADD\n 2.VIEW\n 3,MODIFY NAME\n 4.DELETE\n 5.EXIT")
d={}
while True:
ch=int(input("Enter your choice:"))
if ch==1:
add(d)
elif ch==2:
show(d)
elif ch==3:
mod=int(input("Enter the phone no to be modify:"))
modify(d,mod)
elif ch==4:
delete(d)
elif ch==5:
print("Program terminated")
break
else:
print("Invalid choice")
Output:
Program: 8
d={}
for i in range(4):
d1={}
hn=input("Enter the house name:")
s=int(input("Enter scores of the seniors:"))
j=int(input("Enter the scores of the juniors:"))
sj=int(input("Enter the scores of the sub-juniors:"))
d1['seniors']=s
d1['juniors']=j
d1['sub-juniors']=sj
d[hn]=d1
dk=list(d.keys())
ls,lj,lsj=[],[],[]
for i in dk:
lk=list(d[i].values())
ls+=[lk[0]]
lj+=[lk[1]]
lsj+=[lk[2]]
a=ls.index(max(ls))
b=lj.index(max(lj))
c=lsj.index(max(lsj))
print("Winners of seniors:",max(ls),dk[a])
print("Winners of juniors:",max(lj),dk[b])
print("Winners of sub-juniors:",max(lsj),dk[c])
Program-9
# number.py
def palindrome(n):
if str(n) == str(n)[::-1]:
return 1
else:
return -1
def special(n):
from math import factorial
total = sum(factorial(int(d)) for d in str(n))
if total == n:
return 1
else:
return -1
# main.py
import number
# Check palindrome numbers in a tuple
nums = (121, 456, 1331, 123, 11, 789)
palindromes = [n for n in nums if number.palindrome(n) == 1]
if palindromes:
print("Palindrome numbers in the tuple:")
for p in palindromes:
print(p)
else:
print("No palindrome numbers found.")
# Check special numbers in a range
low = int(input("Enter lower limit: "))
high = int(input("Enter upper limit: "))
specials = [n for n in range(low, high + 1) if number.special(n) == 1]
if specials:
print(f"Special numbers between {low} and {high}:")
for s in specials:
print(s)
else:
print(f"No special numbers found between {low} and {high}.")
Output:
Program: 16
### STACK IMPLEMENTATION###
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()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
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
while True:
print("************ STACK OPERATION***************")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display stack")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
empno=int(input("Enter employee no:"))
name=input("Enter employee name:")
item=(empno,name)
push(stack,item)
elif ch==2:
item=pop(stack)
if item=='Underflow':
print("Underflow!, Stack is empty")
else:
print("Popped item is :",item)
elif ch==3:
item=peek(stack)
if item=='Underflow':
print("Underflow!, Stack is empty")
else:
print("Topmost item is:",item)
elif ch==4:
display(stack)
elif ch==5:
break
else:
print("Invalid Choice")
Output:
Program-17
#[['India','New Delhi'],['Japan','Tokyo'],['USA','Washington DC']]
def insert():
co=input('Enter the country name:')
ca=input('Enter the capital name:')
stack.append([co,ca])
top=stack[-1]
def delete():
if stack==[]:
print('Underflow')
else:
print('Deleted element is',stack.pop())
if len (stack)==0:
top=None
else:
top=stack[-1]
def display():
if stack==[]:
print('Underflow')
return
print('Content of the stack:')
for i in range(len(stack)-1,-1,-1):
print(stack[i])
def peek():
if stack==[]:
print('Underflow')
return
top=stack[-1]
print('The topmost element is :',top)
#main menu
stack=[]
print('''Menu 1.Insert\n 2.Delete\n 3.Display stack \n4.Peek\n 5.Exit''')
while True:
ch=int(input("Enter your choice:"))
if ch==1:
insert()
elif ch==2:
delete()
elif ch==3:
display()
elif ch==4:
peek()
elif ch==5:
print('Exiting')
break
else:
print('Wrong choice')
Output:
Program:11
print("\t Menu")
print('''~~~~~1.Count the number of words
2. Display Palindrome words
3. Display words starting and ending with a vowel
4. Exit~~~~''')
while True:
ch=int(input("Enter your choice:"))
if ch==1:
f=open('F:/Python/text2.txt','r')
cnt=0
s=f.readlines()
for i in s:
j=i.strip().split()
for l in j:
cnt+=1
print('There are',cnt,'words in the file')
f.close()
elif ch==2:
f=open('F:/Python/text2.txt','r')
s=f.readlines()
flag=0
for i in s:
j=i.strip().split()
for l in j:
if l==l[::-1]:
print(l,'is a palindrome word')
flag=1
if flag==0:
print('Ther are no palindrome words in the file')
f.close()
elif ch==3:
f=open('F:/Python/text2.txt','r')
print("The words starting and ending with a vowel are:")
s=f.readlines()
flag=0
for i in s:
j=i.strip().split()
for l in j:
if l[0] in 'aeiouAEIOU' and l[-1] in 'aeiouAEIOU':
print(l)
flag=1
if flag==0:
print('There are no such words in the file')
f.close()
elif ch==4:
break
else:
print("Invalid choice")
Output:
Program:10
f=open('F:/Python/file1.txt')
v=c=u=l=0
data=f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
print("Total no of vowels in file:",v)
print("Total no of consonants in file:",c)
print("Total no of capital letters in file:",u)
print("Total no of small letters in file:",l)
#A file named 'file1.txt' containing:
India is my country,
I love python,
Python learning is fun
Output:
Program:12
import pickle
def write():
f = open('F:/Python/studentdetails.dat', 'wb')
while True:
D = {}
r = int(input("Enter Roll No: "))
n = input("Enter Name: ")
D['Roll No'] = r
D['Name'] = n
pickle.dump(D, f)
ch = input("More? (Y/N): ")
if ch in 'Nn':
break
f.close()
def search():
found = 0
rollno = int(input("Enter roll no to search for name: "))
try:
f = open('F:/Python/studentdetails.dat', 'rb')
while True:
rec = pickle.load(f)
if rec['Roll No'] == rollno:
print("Name:", rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry, not found.")
finally:
f.close()
print("Menu \n 1. Write\n 2. Search \n 3. Exit")
while True:
try:
ch = int(input("Enter your choice: "))
if ch == 1:
write()
elif ch == 2:
search()
elif ch == 3:
break
else:
print("Invalid choice. Please try again.")
except ValueError:
print("Enter a valid number (1-3).")
Output:
Program: 13
import pickle
FILENAME = "F:\\Python\\employee.dat"
def add_employee():
name = input("Enter name: ")
age = int(input("Enter age: "))
department = input("Enter department: ")
designation = input("Enter designation: ")
salary = float(input("Enter salary: "))
employee = {
"name": name,
"age": age,
"department": department.lower(),
"designation": designation.lower(),
"salary": salary
}
with open(FILENAME, "ab") as file:
pickle.dump(employee, file)
print("Employee added successfully.\n")
def display_managers():
found = False
try:
with open(FILENAME, "rb") as file:
print("\nManagers in Finance/Admin earning more than 50000:")
print("-" * 50)
while True:
try:
emp = pickle.load(file)
if emp["designation"] == "manager" and emp["salary"] > 50000 and emp["department"] in
["finance", "admin"]:
found = True
print("Name:", emp["name"])
print("Age:", emp["age"])
print("Department:", emp["department"])
print("Designation:", emp["designation"])
print("Salary:", emp["salary"])
print("-" * 50)
except EOFError:
break
if not found:
print("No matching manager found.\n")
except FileNotFoundError:
print("No employee records found.\n")
def delete_retired_employees():
new_data = []
deleted = False
try:
with open(FILENAME, "rb") as file:
while True:
try:
emp = pickle.load(file)
if emp["age"] < 58:
new_data.append(emp)
else:
deleted = True
except EOFError:
break
with open(FILENAME, "wb") as file:
for emp in new_data:
pickle.dump(emp, file)
if deleted:
print("Retired employees deleted.\n")
else:
print("No retired employees found.\n")
except FileNotFoundError:
print("No employee records found.\n")
def menu():
while True:
print("\n=== Employee Management Menu ===")
print("1. Add Employee")
print("2. Show Managers (Finance/Admin, salary > 50000)")
print("3. Delete Employees Aged 58 or More")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
add_employee()
elif choice == '2':
display_managers()
elif choice == '3':
delete_retired_employees()
elif choice == '4':
print("Thank you! Exiting the program.")
break
else:
print("Invalid choice. Please enter 1 to 4.")
# Start the program
menu()
Output:
Program:14
import csv
with open('F:/Python/id_pass.csv','w') as obj:
fileobj=csv.writer(obj)
fileobj.writerow(["User ID","Password"])
while True:
user_id=input("Enter user Id:")
password=input("Enter password:")
record=[user_id,password]
fileobj.writerow(record)
x=input('PressY/y to continue and N/n to terminate the program:')
if x in 'Nn':
break
else:
continue
with open('F:/Python/id_pass.csv','r',newline="\r\n") as obj2:
fileobj2=csv.reader(obj2)
given=input('Enter the user ID to be searched:')
for i in fileobj2:
if i[0]==given:
print(i[1])
break
Output:
Program:15
import csv
fh=open("F:\\Python\\sports.csv","w")
s=csv.writer(fh,delimiter='\t')
s.writerow(['Sport','Competition','Prizes won'])
ans='y'
i=1
while ans=='y':
print("Record",i)
sport=input("Enter sport name:")
comp=int(input("Enter competitions:"))
prizes=int(input("Enter the prizes:"))
rec=[sport,comp,prizes]
s.writerow(rec)
i=i+1
ans=input("More records?(y/n):")
fh.close()
Output:
Program:18
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
cursor = conn.cursor()
# a) Create the table
cursor.execute("""
CREATE TABLE IF NOT EXISTS student (
Roll INT PRIMARY KEY,
Name VARCHAR(50),
Total FLOAT,
Course VARCHAR(20),
DOB DATE,
CHECK (Course IN ('CS', 'Biology', 'Commerce', 'EG'))
)
""")
print("Table 'student' created successfully.")
# b) Insert records using .format() - NOT recommended for production
records = [
(1, "Alice", 85.5, "CS", "2005-06-12"),
(2, "Bob", 78.0, "Biology", "2004-11-21"),
(3, "Charlie", 92.3, "Commerce", "2005-02-15"),
(4, "David", 67.0, "EG", "2004-09-10"),
(5, "Eva", 88.8, "CS", "2005-12-01")
]
# Insert records one by one using format (again: not secure)
for rec in records:
query = """
INSERT INTO student (Roll, Name, Total, Course, DOB)
VALUES ({}, '{}', {}, '{}', '{}')
""".format(rec[0], rec[1], rec[2], rec[3], rec[4])
cursor.execute(query)
conn.commit()
print("Records inserted using format().")
# c) Display all records
cursor.execute("SELECT * FROM student")
rows = cursor.fetchall()
print("\nStudent Records:")
for row in rows:
print(row)
cursor.close()
conn.close()
output:
Program-19
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="school"
)
cursor = conn.cursor()
# a) Query: max, min total and count per course with >= 2 students
query_a = """
SELECT Course,
MAX(Total) AS MaxTotal,
MIN(Total) AS MinTotal,
COUNT(*) AS StudentCount
FROM student
GROUP BY Course
HAVING COUNT(*) >= 2
"""
cursor.execute(query_a)
results_a = cursor.fetchall()
print("a) Max total, Min total, and number of students per course (where students >= 2):")
for row in results_a:
print("Course: {}, Max Total: {}, Min Total: {}, Number of Students: {}".format(row[0], row[1],
row[2], row[3]))
print("\n" + "-"*50 + "\n")
# Insert a test student for part b using format()
roll = 6
name = "Frank"
total = 150.0
course = "CS"
dob = "2003-05-15"
insert_query = """
INSERT IGNORE INTO student (Roll, Name, Total, Course, DOB)
VALUES ({}, '{}', {}, '{}', '{}')
""".format(roll, name, total, course, dob)
cursor.execute(insert_query)
conn.commit()
# b) Query: students born in May 2003 with total between 100 and 200
year = 2003
month = 5
total_min = 100
total_max = 200
query_b = """
SELECT Roll, Name, Total, Course, DOB
FROM student
WHERE YEAR(DOB) = {}
AND MONTH(DOB) = {}
AND Total BETWEEN {} AND {}
""".format(year, month, total_min, total_max)
cursor.execute(query_b)
results_b = cursor.fetchall()
print("b) Students born in May 2003 with total marks between 100 and 200:")
if results_b:
for row in results_b:
print("Roll: {}, Name: {}, Total: {}, Course: {}, DOB: {}".format(row[0], row[1], row[2], row[3],
row[4]))
else:
print("No students found matching criteria.")
# Close cursor and connection
cursor.close()
conn.close()
Output:
Program-20
import mysql.connector
# Step 1: Connect to MySQL
conn = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='empdatabase'
)
cursor = conn.cursor()
# Step 2: Drop tables in the correct order (child first)
cursor.execute("DROP TABLE IF EXISTS Employee") # Drop child table first
cursor.execute("DROP TABLE IF EXISTS Department") # Then drop parent table
# Step 3: Create Department Table
cursor.execute("""
CREATE TABLE Department (
Deptno INT PRIMARY KEY,
Dname VARCHAR(50),
Location VARCHAR(50)
)
""")
# Step 4: Create Employee Table
cursor.execute("""
CREATE TABLE Employee (
Empno INT PRIMARY KEY,
Name VARCHAR(50),
Desig VARCHAR(50),
Deptno INT,
Salary FLOAT,
FOREIGN KEY (Deptno) REFERENCES Department(Deptno)
)
""")
# Step 5: Insert Data into Department
cursor.execute("INSERT INTO Department VALUES (10, 'HR', 'New York')")
cursor.execute("INSERT INTO Department VALUES (20, 'Finance', 'Chicago')")
cursor.execute("INSERT INTO Department VALUES (30, 'Engineering', 'San Francisco')")
# Step 6: Insert Data into Employee
cursor.execute("INSERT INTO Employee VALUES (101, 'Alice', 'Manager', 10, 80000)")
cursor.execute("INSERT INTO Employee VALUES (102, 'Bob', 'Analyst', 10, 60000)")
cursor.execute("INSERT INTO Employee VALUES (103, 'Charlie', 'Manager', 20, 85000)")
cursor.execute("INSERT INTO Employee VALUES (104, 'David', 'Clerk', 30, 40000)")
cursor.execute("INSERT INTO Employee VALUES (105, 'Eve', 'Manager', 30, 90000)")
conn.commit()
query = """
SELECT E.Empno, E.Name, E.Salary, D.Dname, D.Location
FROM Employee E, Department D
WHERE E.Deptno = D.Deptno AND E.Desig = 'Manager'
"""
cursor.execute(query)
results = cursor.fetchall()
# Step 8: Display the Output
print("Details of all Managers:")
print("Empno Name Salary Dname Location")
for row in results:
print("Empno: {}, Name: {}, Salary: {}, Dname: {}, Location: {}".format(
row[0], row[1], row[2], row[3], row[4]
))
cursor.close()
conn.close()
Output:
Program: 21
create table employee(empno int(6) primary key not null, name varchar(50),dob
date,deptid varchar(5),desig varchar(50), salary int(7));
mysql> insert into employee values(120,'Alisha','1970-01-23','D001','Manager',75000);
mysql> insert into employee values(123,'Nitin','1977-10-10','D002','AO',59000);
mysql> insert into employee values(129,'Navjot','1971-07-
12','D003','Supervisior',40000);
mysql> insert into employee values(130,'Jimmy','1980-12-30','D004','Sales Rep',NULL);
mysql> insert into employee values(131,'Faiz','1984-04-06','D001','Manager',65000);
mysql> select * from employee;
Output:
Program:22
mysql> create table department(deptid varchar(5) primary key not null,deptname
varchar(30), floorno int(3));
mysql> insert into department values('D001','Personal',4);
mysql> insert into department values('D002','Admin',10);
mysql> insert into department values('D003','Production',1);
mysql> insert into department values('D004','Sales',3);
mysql> select * from department;
Output:
Program:23
a) To display the average salary of all employees, department wise.
mysql> select deptid,avg(salary) as "Average Salary" from employee group by deptid;
b) To display name and respective department name of each employee whose salary is more than
50000.
mysql> select e.name,d.deptname from employee e, department d where
e.deptid=d.deptid and salary>50000;
c) To display the name of employees whose salary is not known , in alphabetical order.
mysql> select name from employee where salary is null order by name asc;
d) To display deptid from the employee table without repetition.
mysql> select distinct(deptid) from employee;
e) Select max(salary), desig from employee group by desig;
Program: 24
mysql> create table passenger(pno int(5) primary key not null ,name varchar(20),
gender varchar(7), fno varchar(5));
mysql> insert into passenger values(1001,'Suresh','Male','F101');
mysql> insert into passenger values(1002,'Anita','Female','F104');
mysql> insert into passenger values(1003,'Harjas','Male','F102');
mysql> insert into passenger values(1004,'Nita','Female','F103');
mysql> select * from passenger;
Program: 25
mysql> create table flight(fno varchar(5) primary key not null,start varchar(30),end
varchar(30),fdate date,fare int(5));
mysql> insert into flight values('F101','Mumbai','Chennai','2021-12-25',4500);
mysql> insert into flight values('F102','Mumbai','Bengaluru','2021-11-20',4000);
mysql> insert into flight values('F103','Delhi','Chennai','2021-12-10',5500);
mysql> insert into flight values('F104','Kolkata','Mumbai','2021-12-20',4500);
mysql> select * from flight;
Program: 26
a) Write a query to change the fare to 6000 of the flight FNO is F104.
mysql> update flight set fare=6000 where fno='F104';
Query OK, 1 row affected (1.330 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from flight;
b) Write a query to display the total number of male and female passengers.
mysql> select gender,count(*) from passenger group by gender;
c) Write a query to display the name, corresponding fare and fdate of all passengers
who have a flight to start from delhi.
mysql> select name,fare,fdate from passenger p,flight f where p.fno=f.fno and
start='Delhi';
d) Write a query to delete the records of flight which end at Mumbai.
mysql> delete from flight where end='Mumbai';
Query OK, 1 row affected (1.088 sec)
mysql> select * from flight;
Program: 27
mysql> create table worker( wno int(5) primary key not null, name varchar(40),doj
date,dob date,gender varchar(7),dcode varchar(6));
Query OK, 0 rows affected, 1 warning (7.630 sec)
mysql> insert into worker values(1001,'George k','2013-09-02','1991-09-
01','Male','D01');
mysql> insert into worker values(1002,'Ryma Sen','2012-12-11','1990-12-
15','Female','D03');
mysql> insert into worker values(1003,'Mohitesh','2013-02-03','1987-09-
04','Male','D05');
mysql> insert into worker values(1007,'Anil Jha','2014-01-17','1984-10-19','Male','D04');
mysql> insert into worker values(1004,'Manila Sahai','2012-12-09','1986-11-
14','Female','D01');
mysql> insert into worker values(1005,'R Sahay','2013-11-18','1987-03-31','Male','D02');
mysql> insert into worker values(1006,'Jaya Priya','2014-06-09','1985-06-
23','Female','D05');
mysql> select * from worker;
Program:28
a) To display Wno,Name,Gender from the table WORKER in descending order of
wno.
mysql> select wno,name,gender from worker order by wno desc;
b) To display the Name of all the FEMALE workers from the table worker.
mysql> select name from worker where gender='Female';
c) To display the Wno and Name of those workers from the table worker who are
born between ‘1987-01-01’ and ‘1991-12-01’.
mysql> select wno,name from worker where dob between '1987-01-01' and '1991-12-
01';
d) To count and display male workers who have joined after ‘1986-01-01’.
mysql> select count(*) from worker where gender='Male' and doj > '1986-01-01';