0% found this document useful (0 votes)
31 views35 pages

Record File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views35 pages

Record File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

#PROGRAM NO.

: 1
#PROGRAM NAME: ARITHMETIC OPERATIONS BETWEEN TWO NUMBERS

result = 0
val1= float(input("Enter the first value: "))
val2= float(input("Enter the second value: "))
op=input("Enter any one of the operator(+,-,*,/,//,%): ")
if op=="+":
result=val1+val2
elif op=="-":
result=val1-val2
elif op=="*":
result=val1*val2
elif op=="/":
if val2==0:
print("Please enter a value other than 0")
else:
result=val1/val2
elif op=="//":
result=val1//val2
else:
result=val1%val2
print("The result is: ", result)

#OUTPUT

Enter the first value: 34


Enter the second value: 27
Enter any one of the operator(+,-,*,/,//,%): +
The result is: 61.0
#PROGRAM NO.: 2
#PROGRAM NAME: CHECK PERFECT NUMBER

def pernum(num):
divsum=0
for i in range(1,num):
if num%i==0:
divsum+=i
if divsum==num:
print("Perfect number")
else:
print("Not a perfect number")

n=int(input("Enter any number to check: "))


pernum(n)

#OUTPUT

Enter any number to check: 6


Perfect number

Enter any number to check: 45


Not a Perfect number
#PROGRAM NO.: 3
#PROGRAM NAME: CHECK ARMSTRONG NUMBER

no=int(input("Enter any number to check: "))


no1=no
sum=0
while(no>0):
ans=no%10
sum+=(ans*ans*ans)
no=int(no/10)
if sum==no1:
print("Armstrong Number")
else:
print("Not an Armstrong Number")

#OUTPUT

Enter any number to check: 345


Not an Armstrong Number

Enter any number to check: 1


Armstrong Number
#PROGRAM NO.: 4
#PROGRAM NAME: FIND FACTORIAL OF A NUMBER

num=int(input("Enter the number to calculate its factorial: "))


fact=1
i=1
while i<=num:
fact*=i
i+=1
print("The factorial of",num,"=",fact)

#OUTPUT

Enter the number to calculate its factorial: 7


The factorial of 7 = 5040

Enter the number to calculate its factorial: 5


The factorial of 5 = 120
#PROGRAM NO.: 5
#PROGRAM NAME: FIBONACCI SERIES

i=int(input("Enter the limit: "))


x=0
y=1
z=1
print("Fibonacci series\n")
print(x,y,end=" ")
while(z<=i):
print(z,end=" ")
x=y
y=z
z=x+y

#OUTPUT

Enter the limit: 60


Fibonacci series

0 1 1 2 3 5 8 13 21 34 55
#PROGRAM NO.: 6
#PROGRAM NAME: PALINDROME STRING

msg=input("Enter any string: ")


newlist=[]
newlist[:0]=msg
l=len(newlist)
ed=l-1
for i in range(0,l):
if newlist[i]!=newlist[ed]:
print("Given String is not a palindrome")
break
if i>=ed:
print("Given String is a palindrome")
break
l=l-1
ed=ed-1

#OUTPUT

Enter any string: TENET


Given String is a palindrome

Enter any string: DATA


Given String is not a palindrome
#PROGRAM NO.: 7
#PROGRAM NAME: TRAVERSING A LIST

my_list=['p','r','o','b','e']
print(my_list[0])
print(my_list[2])
print(my_list[4])
n_list=["Happy",[2,0,1,5]]
print(n_list[0][1],n_list[0][2],n_list[0][3])
print(n_list[1][3])

#OUTPUT

p
o
e
a p p
5
#PROGRAM NO.: 8
#PROGRAM NAME: LIST OPERATIONS

memo=[]
for i in range(5):
x=int(input("enter no.: "))
memo.insert(i,x)
i+=1
print(memo)
memo.append(25)
print("Second List")
print(memo)
msg=input("Enter any string: ")
newlist=[]
newlist[:0]=msg
l=len(newlist)
print(l)

#OUTPUT

enter no.: 1
enter no.: 2
enter no.: 3
enter no.: 4
enter no.: 5
[1, 2, 3, 4, 5]
Second List
[1, 2, 3, 4, 5, 25]
Enter any string: PYTHON LEARNING
15
#PROGRAM NO.: 9
#PROGRAM NAME: FLOYD’S TRIANGLE

n=int(input("enter the number: "))


for i in range(n,0,-1):
for j in range(n,i-1,-1):
print(j,end='')
print('\n')

#OUTPUT

Enter the number: 6


6

65

654

6543

65432

654321
#PROGRAM NO.: 10
#PROGRAM NAME: FACTORIAL USING DEFINED MODULE

def fact(no):
f=1;
while no>0:
f*=no
no=no-1
return f
x=int(input("Enter value for factorial: "))
print(fact(x))

#OUTPUT

Enter value for factorial: 9


362880

Enter value for factorial: 4


24
#PROGRAM NO.: 11
#PROGRAM NAME: ARRAY SORTING

arr=[]
def array_sorting():
appendarray()
print()
print('''Sorting techniques
1.Bubble Sort
2.Inserstion Sort''')
ch=int(input("Enter sorting technique: "))
if ch==1:
bubble_sort()
elif ch==2:
insertion_sort()

def appendarray():
n=int(input("Enter the size of array: ")
for i in range(0,n):
x=int(input("enter number: "))
arr.insert(i,x)

def bubble_sort():
print("Original array is: ",arr)
n=len(arr)
list1=[]
for i in arr:
list1.append(i)
for i in range(n):
for j in range(0,n-i-1):
if list1[j]>list1[j+1]:
list1[j],list1[j+1]=list1[j+1],list1[j]
print("Array after bubble sorting is : ",list1)
def insertion_sort():
print("Original array is: ",arr)
list1=[]
for i in arr:
list1.append(i)
for i in range(1,len(arr)):
key=list1[i]
j=i-1
while j>=0 and key<list1[j]:
list1[j+1]=list1[j]
j=j-1
else:
list1[j+1]=key
print("Array after insertion sorting is: ",list1)

array_sorting()

#OUTPUT

Enter the size of array: 6


enter number: 75
enter number: 19
enter number: 46
enter number: 83
enter number: 28
enter number: 64

Sorting techniques
1.Bubble Sort
2.Inserstion Sort
Enter sorting technique: 1
Original array is: [75, 19, 46, 83, 28, 64]
Array after bubble sorting is: [19, 28, 46, 64, 75, 83]
#PROGRAM NO.: 12
#PROGRAM NAME: FILE READING FUNCTIONS

f=open("test.txt","r")
print(f.name)
f_contents=f.read()
print(f_contents)
f_contents=f.readlines()
print(f_contents)
for line in f:
print(line,end="")
f_contents=f.read(50)
print(f_contents)
size_to_read=10
f_contents=f.read(size_to_read)
while len(f_contents)>0:
print(f_contents)
print(f.tell())
f_contents=f.read(size_to_read)

#OUTPUT

test.txt
Hello User
you are working with
Python
Files
#PROGRAM NO.: 13
#PROGRAM NAME: FILE APPENDING FUNCTIONS

af=open("test.txt","a")
lines_of_text=("one line of text here,"+"\t"
"and another line here,"+"\t"
"and yet another here,"+" and so on and so forth")
af.writelines("\n"+lines_of_text)
af.close()

#OUTPUT

Hello User
you are working with
Python
Files

one line of text here, and another line here, and yet another
here, and so on and so forth
#PROGRAM NO.: 14
#PROGRAM NAME: COUNT WORD OCURRENCES IN A FILE

f=open("test.txt","r")
read=f.readlines()
f.close()
times=0
times2=0
chk=input("enter string to search: ")
count=0
for sentence in read:
line=sentence.split()
times+=1
for each in line:
line2=each
times2+=1
if chk==line2:
count+=1
print("the search string",chk,"is present",count,"time(s)")
print(times)
print(times2)

#OUTPUT

enter string to search: Python


the search string Python is present 1 time(s)
6
26
#PROGRAM NO.:15
#PROGRAM NAME: APPEND SPECIFIC WORDS OF FILE

f=open("test.txt",'r')
read=f.readlines()
f.close()
id=[]
for ln in read:
if ln.startswith("T"):
id.append(ln)
print(id)

#OUTPUT

['Test program\n']
#PROGRAM NO.: 16
#PROGRAM NAME: CSV OPERATIONS

import csv
def CreateCSV1():
Csvfile=open('student.csv','w',newline='')
Csvobj=csv.writer(Csvfile)
while True:
Rno=int(input("Rno:"))
Name=input("Name:")
Marks=float(input("Marks:"))
Line=[Rno,Name,Marks]
Csvobj.writerow(Line)
ch=input("More Y/N:")
if ch=='N' or ch=='n':
break;
Csvfile.close()

def CreateCSV2():
Csvfile=open('student.csv','w',newline='')
Csvobj=csv.writer(Csvfile)
Line=[]
while True:
Rno=int(input("Rno:"))
Name=input("Name:")
Marks=float(input("Marks:"))
Line.append([Rno,Name,Marks])
Csvobj.writerow(Line)
ch=input("More Y/N:")
if ch=='N' or ch=='n':
break;
Csvobj.writerows(Line)
Csvfile.close()

def ShowAll():
Csvfile=open('student.csv','r',newline='')
Csvobj=csv.reader(Csvfile)
for Line in Csvobj:
print(Line)
Csvfile.close()

print("CSV file handling")


while True:
option=input("1. create csv 2. Create csv All 3:
Show csv")
if option=="1":
CreateCSV1()
elif option=="2":
CreateCSV2()
elif option=="3":
ShowAll()
else:
break

#OUTPUT

CSV file handling


1. create csv 2. Create csv All 3: Show csv
1
Rno:1
Name:Mohit
Marks:27
More Y/N:n

1. create csv 2. Create csv All 3: Show csv


3
["[1, 'Mohit', 27.0]"]
#PROGRAM NO.: 17
#PROGRAM NAME: STACK OPERATIONS
s=[]
c="y"
while(c=="y"):
print("1.PUSH")
print("2.POP")
print("3.Display")
choice=int(input("Enter your choice: "))
if(choice==1):
a=input("Enter any number: ")
s.append(a)
elif(choice==2):
if(s==[]):
print("Stack Empty")
else:
print("Deleted element is:",s.pop())
elif(choice==3):
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
else:
print("Wrong Input")
c=input("Do you want to continue or not? (y/n): ")
print()

#OUTPUT

1.PUSH
2.POP
3.Display
Enter your choice: 1
Enter any number: 3
Do you want to continue or not? (y/n): y
1.PUSH
2.POP
3.Display
Enter your choice: 1
Enter any number: 5
Do you want to continue or not? (y/n): y

1.PUSH
2.POP
3.Display
Enter your choice: 3
5
3
Do you want to continue or not? (y/n): y

1.PUSH
2.POP
3.Display
Enter your choice: 2
Deleted element is: 5
Do you want to continue or not? (y/n): n
#PROGRAM NO.: 18
#PROGRAM NAME: DISPLAY UNIQUE VOWELS IN WORD USING STACK

vowels=['a','e','i','o','u']
word=input("Enter the word to search of vowels:")
Stack=[]
for letter in word:
if letter in vowels:
if letter not in Stack:
Stack.append(letter)
print(Stack)
print("No. of different vowels present in",word,"is",len(Stack))

#OUTPUT

Enter the word to search of vowels: programming


['o','a','i']
No. of different vowels present in programming is 3
#PROGRAM NO.: 19
#PROGRAM NAME: SQL QUERIES using DDL command

Q.1. Write SQL commands for the following :-


1)
Sr. No. Column_Name Data Type Constraints
1 Pro_Id char(5) Primary Key
2 Pro_Name char(15) Unique Key
3 Qty integer Not Null
4 Price decimal Not Null
5 Rating char(5) -
6 Salesman char(10) -
Create a table ‘Product’ with the given specification.
Ans:- CREATE TABLE Product
( Pro_Id char(5) PRIMARY KEY NOT NULL,
Pro_Name char(15) NOT NULL UNIQUE,
Qty integer NOT NULL,
Price decimal NOT NULL,
Rating char(5),
Salesman char(10)
);

2) Insert following values into the table ‘Product’:


Pro_Id Pro_Name Qty Price Rating Salesman
101 Dairy Milk 100 10 A1 John
102 Five Star 110 15 A1 Jack
103 Milky Bar 50 20 B1 John
104 Munch 200 5 B2 David
105 Perk 25 20 A1 Albert
106 Eclairs 75 2 B1 Sam
107 Bar One 20 5 A2 Sam
108 Borneville 90 25 A1 John
109 Mango Bite 120 1 B2 Albert
110 Coffee 150 2 B1 David
Bite
Ans:- INSERT INTO Product
VALUES(101,’Dairy Milk’,100,10,’A1’,’John’);
INSERT INTO Product
VALUES(102,’Five Star’,110,15,’A1’,’Jack’);
INSERT INTO Product
VALUES(103,’Milky Bar’,50,20,’B1’,’John’);
INSERT INTO Product
VALUES(104,’Munch’,200,5,’B2’,’David’);
INSERT INTO Product
VALUES(105,’Perk’,25,20,’A1’,’Albert’);
INSERT INTO Product
VALUES(106,’Eclairs’,75,2,’B1’,’Sam’);
INSERT INTO Product
VALUES(107,’Bar One’,20,5,’A2’,’Sam’);
INSERT INTO Product
VALUES(108,’Bournville’,90,25,’A1’,’John’);
INSERT INTO Product
VALUES(109,’Mango Bite’,120,1,’B2’,’Albert’);
INSERT INTO Product
VALUES(110,’Coffee Bite’,150,2,’B1’,’David’);
#PROGRAM NO.: 20
#PROGRAM NAME: SQL QUERIES using DML commands

1) Display the description of ‘Product’ table.


Ans:- DESC Product;

2) Display all the types of ‘Product’ table.


Ans:- SELECT * FROM Product;

3) Change the price of the Product with Qty less then 100 to Rs.
10.
Ans:- UPDATE Product
SET Price=10 WHEREQty<100;

4) Display the count of Products with rating A1.


Ans:- SELECT COUNT(*) FROM Product
WHERE Rating=’A1’;

5) Display product name,price and quantity of products whose


price is greater the 100.
Ans:- SELECTPro_Name,Price,QtyFROM Product
WHERE Price>100;

6) Display distinct ratings from ‘Product’.


Ans:- SELECT DISTINCT Ratings FROM Product;

7) Display the minimum price frm Product.


Ans:- SELECT MIN(Price) FROM Product;

8) Display all products sorted by product name.


Ans:- SELECT * FROM Product
ORDER BY Pro_Name;

9) Display product name and (quantity*price) for all products.


Ans:- SELECT Pro_Name, Qty*Price FROM Product;
10) Display the name of salesman whose name starts with ‘J’.
Ans:- SELECT * FROM Product
WHERE Salesman LIKE “J%”;

11) Display product name and rating whose price is between 10 and
20.
Ans:- SELECT Pro_Name, Rating FROM Product
WHERE Price BETWEEN 10 AND 20;

12) Display product id and product name of salesman John, David


and Sam.
Ans:- SELECT Pro_Name, Pro_IdFROM Product
WHERE Salesman IN (‘John’,’David’,’Sam’);

13) Display count of products and sum of price grouped by


salesman.
Ans:- SELECT COUNT(*), SUM(Price) FROM Product
GROUP BY Salesman;
14) Display product id and name with ratings in descending order
and salesman in ascending order.
Ans:- SELECT Pro_Id, Pro_NameFROM Product
ORDER BY Ratings desc, Salesman ASC;

15) Create a new table ‘Item’ with attributes Salesman,Product


Name for Products whose price greater than 10 from ‘Product’
table.
Ans:- CREATE TABLE Item AS
(
SELECT Salesman, Pro_NameFROM Product
WHERE Price>10
);

16) Create view to select product name whose rating is not B1 and
price is greater than 10.
Ans:- CREATE VIEW New AS
SELECT Pro_NameFROM Product
WHERE Rating<>’B1’ AND Price>10;

17) Delete records with price less than or equal to 5.


Ans:- DELETE FROM Product
WHERE Price<=5;

18) Delete the table ‘Product’.


Ans:- DELETE FROM Product;
DROP TABLE Product;
#PROGRAM NO.: 21
#PROGRAM NAME: SQL QUERIES on two tables

EMPLOYEE
Employeei Name Sales Jobid
d
E1 SUMIT SINHA 1100000 102
E2 VIJAY SINGH TOMAR 1300000 101
E3 AJAY RAJPAL 1400000 103
E4 MOHIT RAMNANI 1250000 102
E5 SJAILJA SINGH 1450000 103

JOB
JOBID JOBTITLE SALARY

101 PRESIDENT 20000

102 VICE PRESIDENT 125000

103 ADMINISTRATION 80000


ASSISTANT
104 ACCOUNTING 70000
MANAGER
105 ACCOUNTANT 65000

106 SALES MANAGER 80000

Create a table ‘JOB’:


Ans:- CREATE TABLE JOB
( Jobid int PRIMARY KEY NOT NULL,
Jobtitle varchar(20) NOT NULL,
Salary decimal NOT NULL
);
Create a table ‘EMPLOYEE’:
Ans:- CREATE TABLE EMPLOYEE
( Employeeid char(5) PRIMARY KEY NOT NULL,
Name varchar(20) NOT NULL,
Sales decimal NOT NULL,
Jobid int,
FOREIGN KEY (Jobid)references JOB(Jobid)
);
Write SQL queries for the following:

(i) To display employees ids, names of employees, job ids with


corresponding job titles.
Ans: SELECT Employeeid, Name, Jobtitle
FROM EMPLOYEE, JOB
WHERE EMPLOYEE. Jobid = JOB. Jobid;

(ii) To display names of employees, sales and corresponding job


titles who have achieved sales more than 1300000.
Ans: SELECT Name, Sales, Jobtitle
FROM EMPLOYEE, JOB
WHERE Sales >1300000 AND
EMPLOYEE. Jobid = JOB. Jobid;

(iii) To display names and corresponding job titles of those


employees who have ‘SINGH’ (anywhere) in their names.
Ans: SELECT Name, Jobtitle
FROM EMPLOYEE, JOB
WHERE Name LIKE “%SINGH “ AND
EMPLOYEE. Jobid = JOB. Jobid;

(iv) Write SQL command to change the JOBID to 104 if the EMPLOYEE
with ID as E4 in the table ‘EMPLOYEE’.
Ans: UPDATE EMPLOYEE, JOB
SET EMPLOYEE.Jobid= 104
WHERE Employeeid=E4 AND
EMPLOYEE. Jobid = JOB. Jobid;

(v) Show the average salary for all departments with more than 3
people for a job.
Ans: SELECT AVG(Salary),count(Jobid)
FROM JOB
GROUP BY Jobid
HAVING count(Jobid)>3;

(vi) Display only the jobs with maximum salary greater than or
equal to 3000 job wise.
Ans: SELECT Jobtitle ,MAX(Salary)
FROM JOB
GROUP BY Jobtitle
HAVING MAX(Salary)>= 3000;

(vii) Find out number of employees having “Manager” Job wise.


Ans: SELECT count(Employeeid)
FROM EMPLOYEE
GROUP BY Jobtitle
HAVING Jobtitle=“Manager”;
#PROGRAM NO.: 22
#PROGRAM NAME: SQL QUERIES on two tables
PASSENGER
PNO NAME GENDER FNO
1001 SURESH MALE F101
1002 ANITA FEMALE F104
1003 HARJAS MALE F102
1004 NITA FEMALE F103

FLIGHT
FNO START END F_DATE FARE

F101 MUMBAI CHENNAI 2021-12-25 4500

F102 MUMBAI BANGLURU 2021-11-20 4000

F103 DELHI CHENNAI 2021-12-10 5500

F104 KOLKATA MUMBAI 2021-12-20 4500

i) Write a query to change the fare to 6000 of the flight whose


FNO is F104.
Ans: UPDATE Flight
SET Fare=6000
WHERE Fno=’F104’;
ii) Write a query to display the total number of MALE and FEMALE
PASSENGERS.
Ans: SELECT gender , COUNT(*)
FROM passengers
GROUP BY gender;
iii) Write a query to display the NAME, corresponding FARE and
F_Date of all PASSENGERS who have a flight to STSRT from DELHI.
Ans: SELECT name, fare, f_date
FROM passenger p, flight f
WHERE p.fno=f.fno AND start=”DELHI”;
iv) Write a query to delete the records of flights which end at
Mumbai.
Ans: DELETE FROM flight
WHERE end=”MUMBAI”;
#PROGRAM NO.: 23
#PROGRAM NAME: MYSQL OPERATIONS THROUGH PYTHON

import mysql.connector as MYsql


db1=MYsql.connect(host="localhost",user="root",passwd='',db="empl
oyee")
if db1.is_connected:
print("Successfully connected")

#OUTPUT

Successfully connected
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password
='',db='school')
stmt=con.cursor()
query='select * from student;'
stmt.execute(query)
data=stmt.fetchone()
print(data)

#OUTPUT

(2, ‘Pooja’, 21, ‘Chail’, 390)

#using cursor() method for preparing cursor


cursor=db1.cursor()
#preparing sql statement to create emp table
sql="CREATE TABLE EMP(empno integer primary key, ename
varchar(25) not null, salary float);"
cursor.execute(sql)
db1.close()
#OUTPUT

#Inserting a record in 'emp'


import mysql.connector as MYsql
db1=MYsql.connect(host="localhost",user="root",passwd='',db="empl
oyee")
cursor=db1.cursor()
sql="INSERT INTO EMP VALUES(1,'HET PANDYA',100000);"
try:
cursor.execute(sql)
db1.commit()
except:
db1.rollback()
db1.close()

#OUTPUT
#Fetching all the records from EMP table having salary more than
70000
import mysql.connector as MYsql
db1=MYsql.connect(host="localhost",user="root",passwd='',db="empl
oyee")
cursor=db1.cursor()
sql="SELECT*FROM EMP WHERE salary>80000;"
try:
cursor.execute(sql)
resultset=cursor.fetchall()
for row in resultset:
print(row)
except:
print("Error: unable to fetch data")
db1.close()

#OUTPUT

(1, 'HET PANDYA', 100000.0)

#Updating record(s) of the table using update


import mysql.connector as MYsql
db1=MYsql.connect(host="localhost",user="root",passwd='',db="empl
oyee")
cursor=db1.cursor()
sql="UPDATE EMP SET salary=salary+10000 WHERE salary>80000;"
try:
cursor.execute(sql)
db1.commit()
except:
db1.rollback()
db1.close()
#OUTPUT

#Deleteing record(s) of the table using update


import mysql.connector as MYsql
db1=MYsql.connect(host="localhost",user="root",passwd='',db="empl
oyee")
cursor=db1.cursor()
sal=int(input("Enter salary whose record to be deleted: "))
sql="DELETE FROM EMP WHERE salary="+str(sal)
try:
cursor.execute(sql)
print(cursor.rowcount, end=" record(s) deleted")
db1.commit()
except:
db1.rollback()
db1.close()

#OUTPUT

Enter salary whose record to be deleted: 110000


1 record(s) deleted

You might also like