Wa0000.
Wa0000.
a=eval(input("Enter a list:"))
b=eval(input("Enter the element to be searched:"))lsearch(a,b)
Output:
Enter a list:[1,2,3,1,4,5,6,5]
Enter the element to be searched:1
Found at location: 0
Found at location: 3
frequency of element: 2
Result:
The program is executed and the output is verified.
Program : 2
List traversal
Question:
Write a python program to pass a list to a function to double the odd valuesand half
the even values stored in it.
Aim:
To write a python program to pass a list to a function to double the oddvalues and
half the even values stored in it.
Coding:
def double_half(l):
for i in range(0,len(l)):if
l[i]%2!=0:
l[i]*=2
else:
l[i]/=2
print("Updated list is:",l)
a=eval(input("Enter the list:"))
double_half(a)
Output:
Enter the list:[10,11,12,13,14,15] Updated
list is: [5.0, 22, 6.0, 26, 7.0, 30]
Result:
The program is executed and the output is verified.
Program : 3
Updating a dictionary
Question:
Write a python program to update the value of a dictionary. Obtain thekey
from the user to update the value.
Aim:
To write a python program to input the key and update its value stored in a
dictionary
Coding:
def modify(d,k): value2=eval(input("Enter
the value:"))d[k]=value2
print("Updated dictionary:",d)
Output:
Enter the number of pairs in dictionary:3
Enter the key:"NAME"
Enter the value:"RAMESH"
Enter the key:"AGE"
Enter the value:16
Enter the key:"DESIGNATION"
Enter the value:"Grade 12"
original dictionary is: {'NAME': 'RAMESH', 'AGE': 16, 'DESIGNATION': 'Grade 12'}
Enter the key whose value you want to change:"AGE "Enter the
value:18
Updated dictionary: {'NAME': 'RAMESH', 'AGE': 18, 'DESIGNATION': 'Grade 12'}
Result:
The program is executed and the output is verified.
Program : 4
Printing Factorial value
Question:
Write a python program to print the factorial value of the given number.
Aim:
To write a python program to print the factorial value of the given number.
Coding:
def fact(num):
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from n to 2
fact = fact * num
num-=1
print("Factorial of ", n , " is :",fact)
Result:
The program is executed and the output is verified.
Program : 5
Checking Prime number
Question:
Write a python program to check whether the given number is prime or not.
Aim:
To write a python program to check whether the given number is prime ornot.
Coding:
for i in range(2,int(math.sqrt(num))+1):if
num % i == 0:
isPrime=Falseif
isPrime:
print("## Number is Prime ##\n")
else:
print("## Number is not Prime ##\n")
Output:
Prime or not
************
Enter any number :10
## Number is not Prime ##
Prime or not
************
Enter any number :3 ##
Number is Prime ##
Result:
The program is executed and the output is verified.
Program 6:
Program to search any word in given string/ sentence .
Question :
Write a python program to read a sentence and print the number of timesthe
given word presents in the sentence.
Aim:
To write a python program to read a sentence and print the number oftimes the
given word presents in the sentence.
Coding:
Output:
Result:
The program is executed and the output is verified.
Program: 7
Program to take 10 sample phishing email, and find the mostcommon word
occurring
Question:
Write a python program to take 10 sample phishing emails, and findthe most
common word occurring.
Aim:
To Write a python program to take 10 sample phishing emails, andfind the most
common word occurring.
Coding:
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occurring word is :",key_max)
Output:
Most Common occurring word is : mymoney.com
Result:
The program is executed and the output is verified.
Program : 8
Program to read and display the number of vowel letters present in a text
file.
Question:
Write a python Program to read a text file and display the number ofvowel letters
present in it.
Aim:
To write a python Program to read a text file and display the numberof vowel
letters present in it.
Coding:
def WRITE():
f=open("Sample.txt",'w')
a=['HELLO WORLD',' I LOVE COMPUTER SCIENCE']
f.writelines(a)
f.close()
def READ():
vowels=['a','e','i','o','u']
count=0
f=open("Sample.txt",'r')
b=f.read()
for x in b :
if x.lower() in vowels:
count+=1
print("Number of vowel letters found:",count)f.close()
WRITE()
READ()
Output:
Number of vowel letters found: 12
Result:
The program is executed and the output is verified.
Program : 9
Generating random number
Question:
Write a python program that generates random numbers between the given range.
Aim:
To write a python program that generates random numbers between the given
range.
Coding:
def fun():
import random
lower=int(input("Enter the lower limit:"))
upper=int(input("Enter the upper limit:"))
num=random.randint(lower,upper) print("The
value generated is :", num)
fun()
Output:
Enter the lower limit:1000
Enter the upper limit:1500 The
value generated is : 1468
Result:
The program is executed and the output is verified.
Program : 10
Searching operation in Binary file.
Question :
Write a python Program to Store Student Roll Number, Name, Average in abinary
file and to display the student details whose average is more than 89.
Aim:
To To write a python Program to Store Student Roll Number, Name , Averagein
a binary file and to display the student details whose average is more than 89.
Coding:
Coding:
import pickle
def writedata( ): # To insert n number of data inside the file
f=open("newfile.dat","wb")
li=[]
opt='y'
while opt=='y':
rno=int(input("Enter the roll number:"))
name=input("ENter The Student Name:")
avg=float(input("Enter the average score:"))
li.append([rno,name,avg])
pickle.dump(li,f)
opt=input("press y if you want to add more records:")
f.close()
def search(): # to search and print the students details whose avergae is more than
89
f=open("newfile.dat","rb")
li2=[]
while True:
try:
li2=pickle.load(f)
except EOFError:
break
print("ROLL_NO\tNAME\tAVERGAE")
print("***********************")
for a in li2:
if a[2]>=89:
print(a[0],a[1],a[2], sep="\t")
f.close()
writedata()
search()
Output:
Result:
The program is executed and the output is verified.
Program: 11
Copying the content of one text file into another text
file.
Question:
Write a python Program to read a text file and copying the lines starting with ‘T ‘
or ’t’ into another text file.
Aim:
To write a python Program to read a text file and copying the lines starting with
‘T ‘ or ’t’ into another text file.
Coding:
f=open("D:\source.txt",'r')
f1=open("D:\copy.txt",'w')
line=f.readlines()
for a in line:
if a[0]=='T' or line[0]=='t':
f1.write(a)
f.close()
f1.close()
f2=open("D:\copy.txt",'r')
print("The copied content is:")
content=f2.readlines()
for a in content:
print(a)
f2.close()
Note: Create a text file source.txt and store the below content beforeexecuting the
coding.
Content inside the file source.txt:
**************************************************
Once upon a time,
There was a king called Baratha
Who ruled India.
************************************************
Output:
The copied content is:
There was a king called Baratha
Result:
The program is executed and the output is verified.
Program : 12
Searching operation in a CSV file.
Question:
Write a python Program to create CSV file and store
empno,name,salary and search any empno and display name,salaryand if not
found appropriate message.
Aim:
To write a python Program to create CSV file and store empno,name,salary andsearch any empno
and display name,salary and if not found appropriate message.
Coding:
import csv
with open('myfile.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile.csv',mode='r') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")
Output:
Enter Employee Number 1
Enter Employee Name Subikshan
Enter Employee Salary :30000
## Data Saved... ##
Add More ?y
Enter Employee Number 2
Enter Employee Name Srinivas
Enter Employee Salary :28000
## Data Saved... ##
Add More ?y
Enter Employee Number 3
Enter Employee Name Sabari
Enter Employee Salary :31000
## Data Saved... ##
Add More ?n
Enter Employee Number to search :2
============================
NAME : Srinivas
SALARY : 28000
Result:
The program is executed and the output is verified.
Program : 13
Checking Palindrome string
Question:
Write a python program to check whether the given string is palindrome or
not.
Aim:
To write a python program to check whether the given string is palindrome ornot.
Coding:
print("Python Program to Check a Given String is Palindrome or Not")
Output:
Python Program to Check a Given String is Palindrome or Not
Please enter your own String : malayalam
This is a Palindrome String
Program :14
Counting the number of words present in a text file
Question:
Write a python program to read a text file and print the number ofwords
present in it.
Aim:
To write a python program to read a text file and print the number ofwords
present in it.
Coding:
def WRITE():
f=open("File.txt","w")
content=input("Enter the content( a sentence):")
f.write(content)
f.close()
def COUNTING():
count=0
f=open("File.txt","r")
a=f.read() b=a.split()
print("Total number of words present in the given file is:",len(b))f.close()
WRITE()
COUNTING()
Output:
Enter the content( a sentence):hi how are you
Total number of words present in the given file is: 4
Result:
The program is executed and the output is verified.
def binary_search(arr,
x):low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) //
2 if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
print("Binary Search")
arr =eval(input("Enter a list of numbers in ascending
order:")) x = int(input("Enter the number to be searched:"))
result = binary_search(arr,
x) if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Binary Search
Enter a list of numbers in ascending order:[20,35,68,99,105,200]
Enter the number to be searched:99
Element is present at index 3
Binary Search
Enter a list of numbers in ascending order:[20,35,68,99,105,200]
Enter the number to be searched:205
Element is not present in array
Result:
The program is executed and the output is verified
Program:16
Stack mechanism
Question:
Write a python program to implement stack mechanism
Aim:
To write a python program to implement stack mechanism
Coding:
def PUSH():
n=int(input("Enter the Number:"))
stack.append(n)
t=len(stack)-1def
POP():
if stack==[]:
print("Underflow")
else:
print("The deleted Number is :",stack.pop())
def DISPLAY():
if stack==[]:
print("Underflow")
else:
t=len(stack)-1
while t>=0:
print(stack[t]) t-=1
print("STACK MECHANISM")
stack=[]
t=len(stack)-1
ch='y'
while ch=='y':
Output:
STACK MECHANISM
MENU
1. PUSH
2. POP
3.DISPLAY
4.Exit
Result:
The program is executed and the output is verified
Program : 17
Question : USING GLOBAL KEYWORD INSIDE A FUNCTION DEFINITION
Aim : To use global keyword in function
b=100
def function(x,y):
global b
b=b+100
print("Global variable value inside function:",b)
z=x+y
print("Global variable value before function call:",b)
function(10,20)
print("Global variable value after function call:",b)
Output:
Global variable value before function call: 100
Global variable value inside function : 200
Global variable value after function call:100
Result : The Outputs are verified successfully.
Program : 19
SQL
Question:
Create a table ‘STUDENT’ and execute the queries to fetch result for the given
questions.
Aim:
To create a “STUDENT” table to execute the SQL queries and fetch records for the
given questions.
Creating Database:
create database
student;use student;
Creating Table:
CREATE TABLE STUDENT(RNO INT, NAME CHAR(15),CLASS INT,SCORE FLOAT,RESULT
CHAR(5));
Inserting records:
INSERT INTO STUDENT
VALUES(101,'ARSHATH',12,78,'PASS'); INSERT INTO
STUDENT VALUES(102,'ADARSH',12,65,'PASS'); INSERT
INTO STUDENT VALUES(103,'BINEESH',12,31,'FAIL');
INSERT INTO STUDENT
VALUES(104,'DHARUN',12,50,'PASS'); INSERT INTO
STUDENT VALUES(105,'VIGNESH',12,26,'FAIL');
Questions:
1. Add a column named REMARKS and make its default
value as “NA”. Query: ALTER TABLE STUDENT ADD
REMARKS CHAR(25) DEFAULT 'NA'; Output:
SELECT * FROM STUDENT;
3. Display the Name and Roll Number of the students in descending order of Roll
number.
Query: SELECT RNO,NAME FROM STUDENT ORDER BY RNO DESC;
Output:
Program :18
Question : FINDING NUMBER OF UPPERCASE, LOWERCASE, DIGITS, SPACES AND SPECIAL
CHARACTERS IN A TEXT FILE
Aim : To find the number of uppercase, lowercase, digits, spaces and special characters in a text file.
with open("myfile.txt") as fo:
fc=fo.read()
u=l=d=s=sc=0
for i in fc:
if i.isupper():
u+=1
elif i.islower():
l+=1
elif i.isdigit():
d+=1
elif i==' ':
s+=1
else:
sc+=1
print("No of upper case",u,)
print("No of lower case",l)
print("No of digit case",d)
print("No of space case",s)
print("No of special case",sc)
Result : The Outputs are verified successfully.
4. Write a query to display the number of students got pass and fail marks.
Query: SELECT RESULT, COUNT(*) FROM STUDENT GROUP BY RESULT;
Output:
Result:
The SQL queries were executed and fetched the records successfully.
Program : 20
SQL
Question:
Create the tables ‘PRODUCT’, ‘MANUFACTURER’ and execute the queries to fetch result for the given
questions.
Aim:
To create the tables ‘PRODUCT’, ‘MANUFACTURER’ to execute the SQL queries and fetch records
for the given questions.
Creating database:
create database product;
Creating tables:
CREATE TABLE PRODUCT(PID INT PRIMARY KEY,PNAME CHAR(25),QTY INT,PRICE INT CHECK(PRICE>0));
CREATE TABLE MANUFACTURER(PID INT,COMPANY CHAR(30));
Inserting records:
Table: PRODUCT
INSERT INTO PRODUCT VALUES(101,'KEYBOARD',15,2000);
INSERT INTO PRODUCT VALUES(103,'MOUSE',20,500);
INSERT INTO PRODUCT VALUES(102,'MOTHERBOARD',16,18000);
INSERT INTO PRODUCT VALUES(105,'MODEM',5,8000);
INSERT INTO PRODUCT VALUES(104,'MONITOR',20,14000);
Table: MANUFACTURE
INSERT INTO MANUFACTURER VALUES(101,'LG');
INSERT INTO MANUFACTURER VALUES(102,'IBM');
INSERT INTO MANUFACTURER VALUES(103,'DELL');
INSERT INTO MANUFACTURER VALUES(104,'LENOVO');
INSERT INTO MANUFACTURER VALUES(105,'FIJUTSU');
Questions:
1. Write a query to add a column name “EMAIL” and set its default value as “NOT AVAILABLE”.
Query: ALTER TABLE MANUFACTURER ADD EMAIL VARCHAR(30) DEFAULT 'NOT AVAILABLE';
Output:
Result:
The SQL queries were executed and fetched the records successfully.
Program:21
SQL
Question:
Create a table “TEACHER” and write queries to fetch records fort the given questions.
Aim:
To create a table “TEACHER” to execute the SQL queries and fetch records for the given questions
Creating database:
CREATE DATABASE TEACHER;
USE TEACHER
Creating tables:
CREATE TABLE TEACHER(TID INT, TNAME CHAR(20),SUBJECT CHAR(20),DESIGNATION CHAR(20));
CREATE TABLE DETAILS(TID INT,DOJ DATE,SALARY INT);
Inserting records:
TABLE: TEACHER
INSERT INTO TEACHER VALUES(2001,'ISWARYA','BIOLOGY','PGT');
INSERT INTO TEACHER VALUES(2005,'ANAND','CHEMISTRY','PGT');
INSERT INTO TEACHER VALUES(1007,'SREEMATHI','ECONOMICS','PGT');
INSERT INTO TEACHER VALUES(1009,'MAHATHI','ENGLISH','TGT');
INSERT INTO TEACHER VALUES(2045,'VAISHNAVI','HINDI','PRT');
TABLE:DETAILS
Questions:
1. Write a query to remove the salary column from the table details.
Query & Output:
ALTER TABLE DETAILS DROP COLUMN SALARY;
2. Write a query to display the name of the teacher with corresponding data of joining.
3. Write a query to display the Teachers Name and DOJ in ascending order of DOJ.
5. Write a query to display the name of the Teachers whose starting with the letter ‘M’.
Result:
The SQL queries were executed and fetched the records successfully.
Program : 22 SQL
Question: Create the below given tables and experiment the SQL queries to fetch records for the given
questions.
TABLE: STORE
TABLE: SUPPLIERS
Aim: To create the given tables and experiment SQL queries to fetch the records
Creating database:
CREATE DATABASE STORE;
USE STORE;
Creating tables:
Table STORE:
CREATE TABLE STORE(ITMNO INT,ITEM CHAR(25),SCODE INT,QTY INT,RATE FLOAT,LASTBUY DATE);
Inserting Records:
2. Display ItemNo and Item name of those items from STORE table,whose
Rate is more than Rs 15.
3. Display the details of those items whose Supplier code(Scode) is 22 orQuantity
in store(Qty) is more than 110 from the table STORE.
5. Display the Item Name and Supplier Name with their corresponding SCODE.
Result:
The SQL queries were executed and fetched the records successfully.
Program:23 SQL
Question:
Create the below given table and experiment SQL queries to fetch records for the given questionsTABLE:
HOSPITAL
No Name Age Description Dateofadm Charges Gender
1 Sandeep 65 Surgery 23/02/98 300 M
2 Ravina 24 Orthopedic 20/01/98 200 F
3 Karan 45 Orthopedic 19/02/98 200 M
4 Tarun 12 Surgery 01/01/98 300 M
5 Zubin 36 ENT 12/01/98 250 M
6 Ketaki 16 ENT 24/02/98 300 F
7 Ankita 29 Cardiology 20/02/98 800 F
Aim: to create the given table and pass SQL queries to fetch records for the given questions
Creating database:
CREATE DATABASE HOSP;
USE HOSP;
Creating table:
CREATE TABLE HOSPITAL(NO INT,NAME CHAR(25),AGE INT,DESCRIPTION CHAR(25),DATEOFADMIN
DATE,CHARGES FLOAT,GENDER CHAR(10));
Inserting records:
INSERT INTO HOSPITAL VALUES(1,'SANDEEP',65,'SURGERY','1998-02-23',300,'M');
INSERT INTO HOSPITAL VALUES(2,'RAVINA',24,'ORTHOPEDIC','1998-01-20',200,'F');
INSERT INTO HOSPITAL VALUES(3,'KARAN',45,'ORTHOPEDIC','1998-02-19',200,'M');
INSERT INTO HOSPITAL VALUES(4,'TARUN',12,'SURGERY','1998-01-1',300,'M');
INSERT INTO HOSPITAL VALUES(5,'ZUBIN',36,'ENT','1998-01-12',250,'M');
INSERT INTO HOSPITAL VALUES(6,'KETAKI',16,'ENT','1998-02-24',300,'F');
INSERT INTO HOSPITAL VALUES(7,'ANKITA',29,'CARDIOLOGY','1998-02-28',800,'F');
Questions:
1. Display all information about the patients of Cardiology Department.
Aim:
To create a table “ employee” and retrieve the records through Python-My Sql
connectivity for the below Questions.
Coding:
choice='y'
while choice=='y':
e = int(input("Enter Employee Number”)
n = input("Enter Name :")
d = input("Enter Departmen")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
choice=input("Press y if you want to add more records:")
print("*********************************************************")
Output:
DEPARTMENT , COUNT
('manager', 1)
('auditing', 1)
('sales', 2)
('clerical', 1)
***************************************************
Calculating 15 % Bonus:
NAME BONUS
('Subhikshan', Decimal('10050.00'))
('Tharanees', Decimal('8400.00'))
('Aakash', Decimal('4500.00'))
('Mathan', Decimal('3450.00'))
('Sree', Decimal('3225.00'))
***********************************************
>>>
Result:
Aim:
To create a table “student” and retrieve the records through Python-My Sql
connectivity for the below questions.
Coding:
")
Output:
***********************************************************
Result: