Record 2022

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

EX.

NO:1 Python Program to Calculate Simple Interest from User Input


Program
Amount=int(input("Enter the amount: "))
Year=int(input("Enter the number of years: "))
Rate=float(input("Enter the rate of interest: "))
SimpleInterset=(Amount*Year*Rate)/100
print("The simple interset is: ",SimpleInterset)

Enter the amount: 12000


Enter the number of years: 3
Enter the rate of interest: 8.5
The simple interest is: 3060.0
Result:

Thus the Python program Calculate Simple Interest from User Input executed
successfully and the output is verified.
EX.NO:2 Write a Python program to read a text file line by line and display each
word separated by a ‘#’
Program:
file=open("AI.TXT","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()
Output:

Sample Text File

Python Program Executed Output:

Result:

Thus the Python program to read a text file line by line and display each word
separated by# is executed successfully and the output is verified.
EX.NO:3 Write a Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file
Program:
file=open("AI.TXT","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if (ch in ['a','e','i','o','u']):
vowels+=1
elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are :",vowels)
print("Consonants :",consonants)
print("Lower_case_letters :",lower_case_letters)
print("Upper_case_letters :",upper_case_letters)

Output:

Sample Text File


Python Program Executed Output:

Result:

Thus the Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file is executed
successfully and the output is verified.
EX.NO:4 Write a Python program to create a binary file with name and roll
number and perform search based on roll number.
Program:
#Create a binary file with name and roll number
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of Students:"))
for i in range(no_of_students):
stud_data["roll_no"]=int(input("Enter roll no:"))
stud_data["name"]=input("Enter name: ")
list_of_students.append(stud_data)
stud_data={}
file=open("StudDtl.dat","wb")
pickle.dump(list_of_students,file)
print("Data added successfully")
file.close()

#Search for a given roll number and display the name, if not found display
appropriate message.”
import pickle
file=open("StudDtl.dat","rb")
list_of_students=pickle.load(file)
roll_no=int(input("Enter roll no.of student to search:"))
found=False
for stud_data in list_of_students:
if(stud_data["roll_no"]==roll_no):
found=True
print(stud_data["name"],"found in file.")
if (found==False):
print("No student data found. please try again")
file.close()
Python Program Executed Output:

Result:
Thus the Python program to create a binary file with name and roll number and
perform search based on roll number is executed successfully and the output is
verified.
EX NO:5 Write a program to bubble sort an list of elements
Program
list1=[5,7,2,4,8,9,1,3]
print("The unsorted list is: ", list1)
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
list1[j],list1[j+1]=list1[j+1],list1[j]
print("The sorted list is: ",list1)

output
The unsorted list is: [5, 7, 2, 4, 8, 9, 1, 3]
The sorted list is: [1, 2, 3, 4, 5, 7, 8, 9]

Result:

Thus the Python program bubble sort is executed successfully and the output
is verified.
EX NO:6 Write a Python program to remove all the lines that contain the character
‘a’ in a file and write it to another file.
Program:
file=open("C:\\Users\\Rec\\format.txt","r")
lines=file.readlines()
file.close()
file=open("C:\\Users\\Rec\\format.txt","w")
file1=open("C:\\Users\\Rec\\second.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("Lines containing char 'a' has been removed from format.txt file")
print("Lines containing char 'a' has been saved in second.txt file")
file.close()
file1.close()

Output:
Result:
Thus the Python program to remove all the lines that contain the character
‘a’ in a file and write it to another file is executed successfully and the
output is verified.
EX NO :7 Write a Python program for random number generation that generates
random numbers between 1 to 6 (simulates a dice).
Program:
import random
while(True):
choice=input("Enter 'r' to roll dice or press any other key to quit: ")
if(choice!="r"):
break
n=random.randint(1,6)
print(n)

Output:

Result:
Thus the Python program for random number generation that generates
random numbers between 1 to 6 (simulates a dice) is executed successfully and
the output is verified.
EX NO :8 Write a Python program using function to find the factorial of a natural
number.
Program:
def factorial(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
x=int(input("Enter number: "))
result=factorial (x)
print("Factorial of " ,x, " is :", result)
Output:

Result:
Thus the Python program using function to find the factorial of a natural number
is executed successfully and the output is verified.
EX NO: 9 Write a Python program using function to find the sum of all elements of
a list.
Program:
def sum_list(items):
sum=0
for i in items:
sum=sum+i
return sum

lst=eval(input("Enter list items: "))


print("Sum of list items is : ",sum_list(lst))
Output:

Result:
Thus the Python program using function to find the sum of all elements of a
list is executed successfully and the output is verified.
EX NO:10 Write a program for linear search an element from a list
Program
list1=[1,3,5,4,7,9,2,8]
flag=0
a=int(input("enter the element to search:"))
for i in list1:
if i==a:
flag=1
if flag==1:
print("Element found")
else:
print("Element not found")
Output
enter the element to search:6
Element not found
enter the element to search:3
Element found

Result:
Thus the Python program linear search is executed successfully completed
and the output is verified.
EX NO:11 Write a Python program to implement a Stack using a list data-
structure.
Program:
def push():
a=int(input("Enter the element to be added: "))
stack.append(a)
return a
def pop():
if stack==[]:
print("Stack Underflow!")
else:
print("Deleted element is: ",stack.pop())
def display():
if stack==[]:
print("Stack is Empty!")
else:
for i in range(len(stack)-1,-1,-1):
print(stack[i])

stack=[]
print("STACK OPERATIONS")
choice="y"
while choice=="y":
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
c=int(input("Enter your choice: "))
if c==1:
push()
elif c==2:
pop()
elif c==3:
display()
else:
print("wrong input:")
choice=input("Do you want to continue or not?(y/n): ")

Output:
Result:
Thus the Python program to implement a stack using a list data-structure is
executed successfully and the output is verified.
EX NO:12 Write a Python program to create a CSV file with name and roll
number and perform search for a given roll number and display the name.
Program
import csv
def write():
print("Writing Data into CSV file :")
print("-----------------------------")
f=open("student.csv","w",newline="")
swriter=csv.writer(f)
swriter.writerow(["Name","RollNumber"])
rec=[]
while True:
name=input("Enter Name:")
Roll=int(input("Enter Roll Number:"))
data=[name,Roll]
rec.append(data)
ch=input("Do you want to Enter More Records :(Y/N)?")
if ch in"nN":
break
swriter.writerows(rec)
print("Data write in CSV file successfully")
f.close()

def read():
f=open("student.csv","r")
print("Reading data from csv file")
print("------------------------")
sreader=csv.reader(f)
for i in sreader:
print(i)
def search():
while True:
f=open("student.csv","r")
print("searching data from csv file")
print("------------------------------")
s=input("Enter Rollno to be searched:")
found=0
sreader=csv.reader(f)
for i in sreader:
if i[1]==s:
print(i)
found=1
break
if found==0:
print("sorry...no record found")
ch=input("Do you want to Enter More Records: (Y/N)?")
if ch in "nN":
break
f.close()
write()
read()
search()
Output:

Result:
Thus the Python program to create a CSV file with name and roll number and
perform search for a given roll number and display the name is executed
successfully and the output is verified.
EX NO:13 Write a program to find largest among three integers.
Program
a=int(input('Enter the first integer:'))
b=int(input('Enter the second integer:'))
c=int(input('Enter the third integer:'))
if a>b and a>c:
print(a, 'is the largest integer')
if b>a and b>c:
print(b, 'is the largest integer')
if c>a and c>b:
print(c, 'is the largest integer')
Output

Result:
Thus the Python program to find largest of three numbers is executed
successfully and the output is verified.

EX NO:14 Write a Python program to make user choice to print area of different figure
Program:
def Square():
number=int(input("Enter the side:"))
area=number*number
print("Area of Square:",area)
def Rectangle():
l=int(input("Enter the Length: "))
b=int(input("Enter the Breadth: "))
area=l*b
print("Area of Rectangle:" ,area)
def Triangle():
b=int(input("enter the base of triangle:"))
h=int(input("enter the height of the triangle:"))
area=b*h*.5
print("Area of triangle :",area)
print("Enter the choice 1 for Rectangle 2 for square and 3 for Triangle")
n=int(input("enter the choice:"))
if n==1:
Square()
elif n==2:
Rectangle()
else:
Triangle()

Output:

Enter the choice 1 for Rectangle 2 for square and 3 for Triangle
enter the choice:3
enter the base of triangle:4
enter the height of the triangle:7
Area of triangle : 14.0
Result: Thus the Python program to make user defined module and import same in
another module or program is executed successfully and the output is verified.

EX NO:15 Write a python program to implement python string functions.


Program:
while True:
ch=input("Enter a character:")
if ch.isalpha():
print(ch,"is of alphabets")
elif ch.isdigit():
print(ch,"is a digit")
elif ch.isalnum():
print(ch, "is of aplhabet and numeric")
else:
print(ch,"is of special symbol")
c=input("Do you want to enter more y/n:")
if c in"n":
break
Output:

Result:
Thus the Python program implementing python string functions is executed
successfully and the output is verified.

EX NO:16 Write a Program to integrate SQL with Python by importing the MySQL
module and create a record of employee and display the record.
Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="",databas
e="employee")
cur=con.cursor()
#cur.execute("Create table EMPLOYEE(Eno int,Ename varchar(10),Esal float)")
#print("table created successfully:")
#cur=con.cursor()
while True:
Eno=int(input("Enter Employee Number :"))
Name=input("Enter Employee Name:")
salary=float(input("Enter Employee Salary:"))
query="Insert into employee values({},'{}',{})".format(Eno,Name,salary)
cur.execute(query)
con.commit()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
if ch=="n":
break
cur.execute("select * from employee")
data=cur.fetchall()
for i in data:
print(i)
print("Total number of rows retrieved=",cur.rowcount)

Output:
Result:
Thus the program to integrate SQL with Python by importing the MySQL module
and creating a record of employee and displaying the record is executed
successfully and the output is verified.
EX NO:17 Write a Program to integrate SQL with Python by importing the MYSQL
module to search an employee number in table employee and display record, if
empno not found display appropriate message.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:

print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
Output:

Result:
Thus the program to integrate SQL with Python by importing the MYSQL
module to search an employee number in table employee and display
record, if empno not found display appropriate message is executed successfully
and the output is verified.
EX NO:18 Write a Program to integrate SQL with Python by importing the
MYSQL module to update the employee record of entered empno.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("Enter Empno to update:"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:

print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[
3])
choice=input("\n## Are you sure to update? (Y) :")
if choice.lower()=='y':
print("== You can updatethe details ==")
d = input("Enter new Department:")
if d=="":
d=row[2]
try:
n = input("Enter new Name: ")
s = int(input("Enter new Salary: "))
except:
s=row[3]
query="update employee set name='{}',dept='{}',salary={} where
empno={}".format(n,d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("Do you want to update more? (Y) :")
Output:
Result:
Thus the program to integrate SQL with Python by importing the MYSQL module
to update the employee record of entered empno is executed successfully and
output verified.
EX NO:19 Write a Program to integrate SQL with Python by importing the MYSQL
module to delete the record of entered employee number.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:

print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[
3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
Output:

Result:
Thus the program to integrate SQL with Python by importing the MYSQL module
to delete the record of entered employee number is executed successfully and
output verified.
MYSQL 1

Table : products
+-----------+-------------+-----------+----------+-------+-------+-------+------------
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+-------+-------+-------
| 1001 | PEN | Pen Red | 5000 | 1.23 |
| 1002 | PEN | Pen Blue | 8000 | 1.25 |
| 1003 | PEN | Pen Black | 2000 | 1.25 |
| 1004 | PEC | Pencil 2B | 10000 | 0.48 |
| 1005 | PEC | Pencil 2H | 8000 | 0.49 |
1) Select the table where price less than 1.0
mysql> SELECT name, price FROM products WHERE price < 1.0;
+-----------+-------+
| name | price |
+-----------+-------+
| Pencil 2B | 0.48 |
| Pencil 2H | 0.49 |
+-----------+-------+
2) Select the table where quantity less than or equal to 2000

Mysql>SELECT name, quantity FROM products WHERE quantity <= 2000;


+-----------+----------+
| name | quantity |
+-----------+----------+
| Pen Black | 2000 |
+-----------+----------+
3) Select the table where name start with ‘pencil’

mysql> SELECT name, price FROM products WHERE name LIKE 'PENCIL%';
| name | price |
| Pencil 2B | 0.48 |
| Pencil 2H | 0.49 |

4) Select the table only name in Pen Red and Pen Black

Mysql> SELECT * FROM products WHERE name IN ('Pen Red', 'Pen Black');
+-----------+-------------+-----------+----------+-------+--------+----------
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+--------+----------
| 1001 | PEN | Pen Red | 5000 | 1.23 |
| 1003 | PEN | Pen Black | 2000 |1.25 |
+-----------+-------------+-----------+----------+-------+-------+----------
5) Increase the price by 10% for all products
mysql> UPDATE products SET price = price * 1.1;

mysql> SELECT * FROM products;


+-----------+-------------+-----------+----------+-------+------------------
| productID | productCode | name | quantity | price |
+-----------+-------------+-----------+----------+-------+------------------
| 1001 | PEN | Pen Red | 5000 | 1.35 |
| 1002 | PEN | Pen Blue | 8000 | 1.38 |
| 1003 | PEN | Pen Black | 2000 | 1.38 |
| 1004 | PEC | Pencil 2B | 10000 | 0.53 |
| 1005 | PEC | Pencil 2H | 8000 | 0.54 |
+-----------+-------------+-----------+----------+-------+------------------

MYSQL 2
Table : Information

firstname lastname gender grade dob

Amanda Williams f 10 1999-03-30

Peter Williams m 10 1998-03-15

Cristie Wills f 10 1999-02-05

1) Adding a Column to the Table

mysql>ALTER TABLE Information ADD rollnumber INT;

2) Counting the Number of Rows

mysql> SELECT COUNT (*) FROM Information;

count(*)

3) Selecting Particular Records

mysql> SELECT * FROM Information WHERE lastname = 'Williams';

firstname lastname gender grade dob

Amanda Williams f 10 1999-03-30

Peter Williams m 10 1998-03-15

4) Updating Selected Records


mysql> UPDATE Information SET dob = '1999-02-02' WHERE lastname = ‘Wills’;.

lastnam
firstname gender grade dob
e

Cristie Wills f 10 1999-02-02

5) Delete a record

mysql>DELETE from information WHERE firstname=’Peter’

Query OK ,1 row affected(0.07 sec)

MYSQL 3
Table : shop

+---------+--------+-------+

| article | dealer | price |

+---------+--------+-------+

0001 A 3.45

0001 B 3.99

0002 A 10.99

0003 B 1.45

0003 C 1.69

0003 D 1.25

0004 D 19.95

1) Select the maximum price from the table

mysql>SELECT MAX(price) FROM shop;

| MAX(price) |

+---------+

| 19.95 |

2) Select the table descending order by price.

mysql>SELECT * FROM shop ORDER BY price DESC;

| article | dealer | price |

0004 D 19.95

0002 A 10.99

0001 B 3.99
0001 A 3.45

0003 C 1.69

0003 B 1.45

0003 D 1.25

3) Find the highest price per article.

mysql>SELECT article, MAX(price) FROM shop GROUP BY article;

| article | price |

+---------+-------+

| 0001 | 3.99 |

| 0002 | 10.99 |

| 0003 | 1.69 |

| 0004 | 19.95 |

4) Select average price from the table shop.

mysql> SELECT AVG(price) FROM shop

AVG(price)

| 6.11 |

5) Delete a record from shop table.

mysql>Delete from shop where article=0002;

MYSQL 4
Table :Employee

1) Adding one more Field to Employee table.

mysql> Alter table employee add(doj date);

Query OK, 7 rows affected (0.03 sec)

2) Checking null value in Dept.

mysql> Select * from emp where Dept is null;

Empty set (0.00 sec)


3) List the entire employee whose department is “Accounts”.
mysql>Select * from employee where Dept='Accounts';

4) Check for the uniqueness of Dept.


mysql> Select Distinct Dept from Employee;
5) Delete a record from the table employee.
mysql> DELETE from employee where Empno=1223;
Query OK, 1 row affected (0.01 sec)

MYSQL 5
Table 1: DEPT
DCODE DEPARTMENT CITY
D01 Media Delhi
D02 Marketing Delhi
D03 Infrastructure Mumbai
D04 Human resource Mumbai
D05 Finance Kolkata

Table 2: WORKERS
DCODE NAME DOB GENDER
D01 George K 1991-09-01 Male
D03 Ryma Sen 1990-12-15 Female
D05 Mohitesh 1987-09-04 Male
D04 Anil jha 1984-10-19 Male
D01 Manila Sahai 1986-11-14 Female
D02 R Sahay 1987-03-31 Male
D05 Jaya Priya 1985-06-23 Female
1) To display Name,DOB,Gender from table WORKERS descending order of Name.
Mysql> SELECT Name,Dob,Gender from WORKERS ORDER BY Name DESC;
NAME DOB GENDER
Ryma Sen 15-12-1990 Female
R Sahay 31-03-1987 Male
Mohitesh 4-09-1987 Male
Manila Sahai 14-11-1986 Female
Jaya Priya 23-06-1985 Female
George K 1-09-1991 Male
Anil jha 19-10-1984 Male

2) To display the name of all the FEMALE workers from the table WORKERS.
Mysql>SELECT Name FROM WORKERS WHERE GENDER=’Female’;
NAME

Ryma Sen
Manila Sahai
Jaya Priya
3) Select distinct city from table DEPT.
Mysql>SELECT DISTINCT(CITY) from DEPT;
CITY
Delhi
Mumbai
Kolkata
4) To display the DCODE ,NAME of those workers from the WORKERS table who
are born between ‘1987-01-01’ and ‘1991-12-01’
Mysql>SELECT DCODE ,NAME from the WORKERS where DOB BETWEEN ‘1987-01-
01’ and ‘1991-12-01’;
DCODE NAME
D01 George K
D03 Ryma Sen
D05 Mohitesh
D02 R Sahay
5) To display NAME, DOJ from WORKERS table and DEPARTMENT ,CITY FROM
DEPT table whose DCODE are equal.
Mysql> SELECT NAME,DOJ,DEPARTMENT,CITY FROM WORKERS W,DEPT D
WHERE W.DCODE=D.DCODE;
NAME DOB DEPARTMENT CITY
George K 1/09/1991 Media Delhi
Ryma Sen 15/12/1990 Infrastructure Mumbai
Mohitesh 4/09/1987 Finance Kolkata
Anil jha 19/10/1984 Human resource Mumbai
Manila 14/11/1986 Media Delhi
Sahai
R Sahay 31/03/1987 Marketing Delhi
Jaya Priya 23/06/1985 Finance Kolkata

You might also like