0% found this document useful (0 votes)
7 views90 pages

INDEX Merged

The document is a practical record for AKR Academy School (CBSE) for the academic year 2024-25, detailing various programming exercises and algorithms in Python. It includes topics such as arithmetic calculators, sorting algorithms, searching techniques, and file handling using CSV and binary files. Each exercise provides an aim, algorithm, source code, and output results, demonstrating the execution of Python programs.

Uploaded by

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

INDEX Merged

The document is a practical record for AKR Academy School (CBSE) for the academic year 2024-25, detailing various programming exercises and algorithms in Python. It includes topics such as arithmetic calculators, sorting algorithms, searching techniques, and file handling using CSV and binary files. Each exercise provides an aim, algorithm, source code, and output results, demonstrating the execution of Python programs.

Uploaded by

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

AKR ACADEMY SCHOOL (CBSE)

ANAIPUDUR, AVINASHI 641 652

PRACTICAL RECORD

2024-25

NAME :

REG. NO :

CLASS & SEC :

INTERNAL EXTERNAL PRINCIPAL


INDEX

S.NO. TOPICS P.NO SIGNATURE


1 ARITHMETIC CALCULATOR

2 ARMSTRONG NUMBER

3 BUBBLE SORT

4 INSERTION SORT

5 LINEAR SEARCH

CREATE A CSV FILE TO SEARCH AND


6
DISPLAY THE DETAILS

LARGEST AND SMALLEST ELEMENT IN


7
A LIST

DOUBLE THE ODD VALUES AND HALF


8
THE EVEN VALUES

COUNT THE NUMBER OF ODD NUMBERS


9
AND EVEN NUMBERS

10 MUTABILITY USING LIST

11 UPDATING DICTIONARY USING KEYS

COUNT TOTAL NUMBER OF VOWELS IN


12
STRING
SEARCH THE LOWER CASE, UPPER
13 CASE AND OTHER CHARACTER INA FILE AND WRITE IT IN
RESPECTIVE FILES

CREATE A BINARY FILE WITH NAME


& ROLL NUMBER SEARCH FOR A GIVEN
14
ROLL NUMBER AND DISPLAY NAME, IF NOT FOUND DISPLAY A
MESSAGE

CREATE A BINARY FILE WITH ROLL


15 NUMBER, NAME AND MARKS, INPUT A ROLL NUMBER AND UPDATE
THE MARK

TO REMOVE ALL THE LINES THAT


16
CONTAIN LETTER 'A' IN A FILE AND WRITE IT INTO ANOTHER FILE

READ AND DISPLAY FILE CONTENT


17
LINE BY LINE WITH EACH WORD SEPARATED BY #

READ A LINE AND COUNT THE NUMBER


18
OF UPPERCASE, LOWERCASE, ALPHABETS AND DIGITS

19 STACK OPERATION

- INTEGRATE PYTHON
WITH MYSQL

20 FETCHING RECORDS FROM TABLE

21 COUNTING A RECORD FROM TABLE

22 SEARCHING A RECORD FROM TABLE

23 DELETING A RECORD FROM TABLE

- SQL QUERIES

24 TABLE: STATIONERY AND CONSUMER

25 TABLE: ITEM AND TRADERS

26 TABLE: DOCTOR AND SALARY


EX.NO:1 ARITHMETIC CALCULATOR
DATE:

AIM:

Program to enter two numbers and print the arithmetic operations like + , - , *
, / , // and %

ALGORITHM:

STEP 1 : Declare a variable result=0.

STEP 2 : Get val1 and val2 from user.

STEP 3 : Get the operator from the user (+ , - , * , / , // , %).

STEP 4 : If op==”+” , then add the two numbers.

STEP 5 : If op==”-” , then subtract the two numbers.

STEP 6 : If op==”*” , then multiply the two numbers.

STEP 7 : If op==”/” , then divide the two numbers.

STEP 8 : If op==”//” , then calculate the floor division.

STEP 9 : If op==”%” , then calculate the modulus value.

STEP 10 : Print the result.

STEP 11 : Save and execute the program.


1. ARITHMETIC CALCULATOR

SOURCE CODE:

result=0

val1= float(input("ENTER THE FIRST VALUE"))

val2= float(input("ENTER THE SECOND VALUE"))

OP= input("ENTER ANY ONE OF THR OPERATOR(+,-,*,/,//,%)")

if OP=="+":

result=val1+val2

elif OP=="-":

result=val1-val2

elif OP=="*":

result=val1*val2

elif OP=="/":

result=val1/val2

elif OP=="//":

result=val1//val2

else:

result=val1%val2

print("The Result Is",result)


1 .ARITHMETIC CALCULATOR

OUTPUT :

RESULT :

Thus , the above python code was typed and executed successfully
EX.NO:2 ARMSTRONG NUMBER
DATE:

AIM:

Write a program to check if the entered number is Armstrong or not.

ALGORITHM:

STEP 1 : Get the number from the user(num).

STEP 2 : Declare the variable sum=0.

STEP 3 : Assign the num value to temp variable.

STEP 4 : Divide the given number into individual digit(For example , Divide 370
into 3, 7, 0) .

STEP 5 : Calculate the power of n for each individual and add those numbers.

STEP 6 : Compare original value with Sum value.

STEP 7 : If they exactly matched then it is Armstrong number else it is not


Armstrong.

STEP 8 : Save and execute the program.


2. ARMSTRONG NUMBER

SOURCE CODE:

num= int(input("ENTER THE NUMBER"))

sum= 0

temp=num

while temp>0:

digit=temp%10

sum+=digit**3

temp//=10

if num==sum:

print(num,"IS AN ARMSTRONG NUMBER")

else:

print(num,"IS NOT AN ARMSTRONG NUMBER")


2 .ARMSTRONG NUMBER

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 3
BUBBLE SORT
DATE:

AIM:

To sort the given list using bubble sort.

ALGORITHM:

STEP 1: Get the list from the user.

STEP 2:Calculate the length of the list and store it in the variable n.

STEP 3: Create a loop with a variable i that counts from length of the list(n).

STEP 4: Create a inner loop with a loop variable that counts from 0 up to n-i-1.

STEP 5: Inside the inner loop, if the elements at indexes j and j+1 are out of order,
then swap them.

STEP 6:If in one iteration of the inner loop there were no swaps, then the list is
sorted and one can return prematurely.
3. BUBBLE SORT

SOURCE CODE:

alist=eval(input("enter a list within square brackets:"))

print("original list is:",alist)

n=len(alist)

for i in range(n):

for j in range(0,n-i-1):

if alist[j]>alist[j+1]:

alist[j],alist[j+1]=alist[j+1],alist[j]

print("list after sorting:",alist)


3 .BUBBLE SORT

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 4
DATE: INSERTION SORT

AIM:

To sort the given list by insertion sort.

ALGORITHM:

STEP 1:Get the list from the user.

STEP 2:Create a loop with a variable I that counts from 1 to the length of the list.

STEP 3:Set key equal to the element at index i.

STEP 4:Set j equal to i-1.

STEP 5:Create a while loop that runs as long as j is non-negative and key is smaller
than the element at index j.

STEP 6:Inside the while loop, set the element at index j+1 equal to the element at
index j and decrement j.

STEP 7:After the while loop finishes, set the element at index j+1 equals to key.

STEP 8:Save and execute the program.


4. INSERTION SORT

SOURCE CODE:

alist=eval(input("enter a list within square brackets:"))

print("original list is:",alist)

for i in range(1,len(alist)):

key= alist[i]

j=i-1

while j>=0 and key<alist[j]:

alist[j+1]=alist[j]

j-=1

else:

alist[j+1]=key

print('List after sorting:',alist)


4 .INSERTION SORT

Output :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 5 LINEAR SEARCH
DATE:

AIM:

The program takes a list and item as input and finds the index of the item in
the list using linear search.

ALGORITHM:

STEP 1:Get a list size n, and to get elements one by one using for loop and store it
array.

STEP 2:Get a search element.

STEP 3:Create a function lsearch for receive a list and item as arguments.

STEP 4:A loop iterates through the list and when an item matching the key is
found, the corresponding index is returned.

STEP 5:If no such item is found, False is returned.

STEP 6:Save and execute the program.


5. LINEAR SEARCH

SOURCE CODE:
def lsearch(ar,item):

i=0

while i<len(ar) and ar[i]!=item:

i+=1

if i<len(ar):

return i

else:

return False

n=int(input("Enter desired linear listsize(max.50)..."))

print("\Enter elements for linear list\n")

ar=[0]*n

for i in range(n):

ar[i]=int(input("Element"+str(i)+":"))

item=int(input("\nEnter element to be searched for..."))

index=lsearch(ar,item)

if index:

print("\nElement found at index:",index,",position:",(index+1))

else:

print("\nSorry!!Given element could not be found.\n")


5 .LINEAR SEARCH

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 6 CREATE A CSV FILE TO SEARCH
DATE:
AND DISPLAY THE DETAILS

AIM:

The program takes a list and item as input and finds the index of the item in
the list using CSV.

ALGORITHM:

STEP 1:Import the CSV module

STEP 2:Using ‘with’ keyword open a file employee.txt in append mode.

STEP 3:Create a while loop to collect the data regarding employee id, employee
name, employee mobile number.

STEP 4:Use writerow() to add the details to the file, employee.

STEP 5:Open another file in read mode.

STEP 6:Open while loop and create a variable e which asks the user for the
employee id they have to search for.

STEP 7: Using for loop iterate myreader. Open if condition for len(row)!=0 which
has another if condition for int(row[0])==e.

STEP 8:If not found print Employee ID not found.

STEP 9:In the variable, ans ask whether the user wants to search more using the
keyword input.
6. CREATE A CSV FILE TO SEARCH AND DISPLAY
THE DETAILS

SOURCE CODE:

import csv

with open('employee.txt','a') as csvfile:

mywriter= csv.writer(csvfile,delimiter=',')

ans='y'

while ans.lower()=='y':

eno=int(input('Enter Employee ID:'))

name= input('Enter Employee name:')

mobno= int(input('Enter Employee Mobile No:'))

mywriter.writerow([eno,name,mobno])

ans=input('Do you want to enter more data?(y/n):')

csvfile.close()

ans='y'

with open('employee.txt','r') as csvfile:

myreader=csv.reader(csvfile,delimiter=',')

ans='y'

while ans.lower()=='y':

found=False

e= (input('Enter Employee ID to search:'))

for row in myreader:


if len(row)!=0:

if (row[0])==e:

print('name:',row[1])

print('Mobile No:',row[2])

found=True

break

if not found:

print('Employee ID not found')

ans=input('Do you want to search more?(y/n):')

ans='y'
6 .CREATE A CSV FILE TO SEARCH AND DISPLAY THE
DETAILS

OUTPUT :

RESULT :

Thus , the above python code was typed and executed successfully
EX.NO: 7 LARGEST AND SMALLEST
DATE: ELEMENT IN A LIST

AIM:

To find largest and smallest element in a given list.

ALGORITHM:

STEP 1: Get a list from the user.

STEP 2: Create a function bubble sort that takes a list as argument.

STEP 3: Inside the function create a loop with a loop variable I that counts from
the length of the list.

STEP 4: Create an inner loop with a loop variable that counts from 0 up to n-i-1.

STEP 5: Inside the inner loop, if the element at indexes j and j+1 are out of order,
then swap them.

STEP 6: If in one iteration of the inner loop there were no swaps, then list is
sorted and one can return prematurely.

STEP 7: Print a result as [0]th index value as smallest number in a list and [-1]th
index value as largest number in a list.

STEP 8: Save and execute the program.


7. LARGEST AND SMALLEST ELEMENT IN A LIST

SOURCE CODE:

def bubbleSort(lst):

n=len(lst)

for i in range(n):

for j in range(0,n-i-1):

if lst[j]>lst[j+1]:

lst[j],lst[j+1]=lst[j+1],lst[j]

x=list(eval(input("enter a list")))

bubbleSort(X)

print("smallest no.:",x[0],"largest no.:",x[-1])


7 .LARGEST AND SMALLEST IN A LIST

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 8 DOUBLE THE ODD VALUES AND
DATE: HALF THE EVEN VALUES

AIM:

To pass a list and double the odd values and half the even values and display
the changed list.

ALGORITHM:

STEP 1: Define a function f.

STEP 2: Get the list from the user.

STEP 3: Invoke a function f with the argument (a).

STEP 4: A function receives a parameter (a) and initialize an empty list l2.

STEP 5: Create a for loop with a variable I, range(0,len(b)).

STEP 6: if b[i]%2==0, e=b[i]/4, e is appended in l2.

STEP 7: If the above condition gets false else block gets executed as e=b[i]*2 and
e gets appended to l2 and prints the list l2.

STEP 8: Stop the process.


8. DOUBLE THE ODD VALUES AND HALF THE
EVEN VALUES

SOURCE CODE:

def f(b):

l2=[]

for i in range(0,len(b)):

if b[i]%2==0:

e=b[i]/2

l2.append(e)

else:

e=b[i]*2

l2.append(e)

print(l2)

a=eval(input("enter a list:"))

f(a)
8 .DOUBLE THE ODD VALUES AND HALF THE EVEN
NUMBERS

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 9 COUNT THE NUMBER OF ODD
DATE: NUMBERS AND EVEN NUMBERS

AIM:

To input n numbers in a tuple & count how many even & odd numbers are
entered.

ALGORITHM:

STEP 1: Define a function x.

STEP 2: Get the list from the user.

STEP 3: Initialize variables namely e and o as e=0 and o=0

STEP 4: Create a for loop with variable i, range(0,len(l)).

STEP 5: If, l[i]%2==0 , e+=1 : Else, o+=1

STEP 6:”Number of even numbers:”,e,”Number of odd numbers:”,o,gets printed.

STEP 7: Stop the process.


9. COUNT THE NUMBER OF ODD AND EVEN
NUMBERS

SOURCE CODE:

def fun(l):

e=0

o=0

for i in range(0,len(l)):

if l[i]%2 == 0:

e+=1

else:

o+=1

print('Number of even numbers:',e)

print('Number of odd numbers:',o)

x = eval(input('Ente a tuple:'))

fun(x)
9 .COUNT THE NUMBER OF ODD NUMBERS AND
EVEN NUMBERS

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 10
MUTABILITY USING LIST
DATE:

AIM:

Passing a mutable type list to a function –Making changes in a place.

ALGORITHM:

STEP 1: Define a function myfunc.

STEP 2: Initialize a list, list l=1,var l=1

STEP 3: The statement “values/variables before function call:”, listl, varl” gets
printed.

STEP 4: The received parameters execute the function l[0]+=2 v+=2

STEP 5: The print statement prints the statement “variables/values within called
function:”,l, v. Then the “return” keyword is executed but does not return any
values as there is no assignment of identifiers.

STEP 6: Stop the process and execute the program to get the output
10. MUTABILITY USING LIST

SOURCE CODE:

def myfunc(l,v):

l[0]+=2

v+=2

print("variable/values within called funtion:",l,v)

return

#_main_

list1=[1]

varl=1

print("values/variables before function call:",list1,varl)

myfunc(list1,varl)

print("values/variables after function call:",list1,varl)


10 .MUTABLITY USING LIST

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 11 UPDATING DICTIONARY USING
DATE: KEYS

AIM:

To update dictionary using keys by defining functions.

ALGORITHM:

STEP 1: Define a function fun.

STEP 2: Get the number of pairs present in dictionary from user using input
method.

STEP 3: Declare an empty dictionary dic and create a for loop with variable I, in
range(x).

STEP 4: Get the required key and value from the user and assign the value to the
respective keys using dic[key]=value.

STEP 5: The for loop exists and prints the original dictionary using the print
statement.

STEP 6: Get the key whose value you want to change from the user using the
input method.

STEP 7: Function call takes place by getting the arguments (dic,a)

STEP 8: Get the values from the user and change the needed value (d[k]=value2)

STEP 9: Print statement prints (“Updated dictionary:”,d)

STEP 10: Stop the process and execute the codes.


11. UPDATING DICTIONARY USING KEYS

SOURCE CODE:

def fun(d,k):

value2=eval(input("Enter the values:"))

d[k]=value2

print("Updated dictionary:",d)

x=int(input("number of pairs in dictionary:"))

dic={}

for i in range(x):

key=eval(input("Enter the key:"))

value=eval(input("Enter the value:"))

dic[key]=value

print("Original dictionary:",dic)

a=(eval(input("Enter the key whose value you to change:")))

fun(dic,a)
11 .UPDATING DICTIONARY USING KEYS

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 12 COUNT TOTAL NUMBER OF
DATE: VOWELS IN STRING

AIM:

To count total number of vowels in string.

ALGORITHM:

STEP 1: Define a function f1.

STEP 2: Get a string from the user by using input method

STEP 3: Then the function call takes place by passing an argument “a”.

STEP 4: The argument is received in the function definition by the parameter “b” and then an
identifier “count=0” is initialized.

STEP 5: The for loop is created as range (0,len(b)).The if conditional statements are added in the
function block as follows:

B*i+==’a’ or b*i+==’A’:
Count+=1
If B*i+==’e’ or b*i+==’E’:
Count+=1
If B*i+==’i’ or b*i+==’I’:
Count+=1
If B*i+==’o’ or b*i+==’o’:
Count+=1
If B*i+==’u’ or b*i+==’U’:
Count+=1
STEP 6: After the execution of the conditional statements the, the print statement prints
(“Number of vowels in string”, count).

STEP 7: Save and execute the program.


12. COUNT TOTAL NUMBER OF VOWELS IN
STRING

SOURCE CODE:

def f1(b):

count=0

for i in range (0,len(b)):

if b[i]=='a' or b[i]=='A':

count+=1

if b[i]=='e' or b[i]=='E':

count+=1

if b[i]=='i' or b[i]=='I':

count+=1

if b[i]=='o' or b[i]=='O':

count+=1

if b[i]=='u' or b[i]=='U':

count+=1

print("Number of vowels in string",count)

a=eval(input("Enter a string"))

f1(a)
12 .COUNT TOTAL NUMBER OF VALUES IN A STRING

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
SEARCH THE LOWER CASE, UPPER
EX.NO: 13 CASE AND OTHER CHARACTER IN A
DATE: FILE AND WRITE IT IN RESPECTIVE
FILES

AIM:

To search the lower case, upper case and other character in a file and write it
in respective files.

ALGORITHM:

STEP 1: Open three text files ‘LOWER’,’UPPER’ and ‘OTHERS’ with file handle as
f1,f2 and f3 in write mode.

STEP2: Display ‘input ”~”to stop execution’. To break the while loop.

STEP 3:In a while loop, get a single character as input from user and assign it to a
variable ‘c’.

STEP 4:If the user inputs ‘~’, break the loop.

STEP 5:If the entered character is lower case, write the character in the file f1, if it
is upper case, write the character in the file f3.

STEP 6:Close all the files.

STEP 7:Save and execute the program.


13. SEARCH THE LOWERCASE, UPPERCASE AND
OTHER CHARACTER IN A FILE AND WRITE IT
IN RESPECTIVE FILES

SOURCE CODE:

f1= open('LOWER.txt','w')

f2= open('UPPER.txt','w')

f3= open('OTHERS.txt','w')

print('input "~" to stop execution')

while True:

c = input('Enter a single character:')

if c=='~':

break

elif c.islower():

f1.write(c)

elif c.isupper():

f2.write(c)

else:

f3.write(c)

f1.close()

f2.close()

f3.close()
13 .SPERATING LOWERCASE , UPPERCASE AND
OTHER CHARACTERS

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
CREATE A BINARY FILE WITH NAME &
EX.NO: 14 ROLL NUMBER, SEARCH FOR A GIVEN
DATE: ROLL NUMBER AND DISPLAY NAME, IF
NOT FOUND DISPLAY A MESSAGE

AIM:

Create a binary file with name &roll number, search for a given roll number and display
name, if not found display a message.

ALGORITHM:

STEP 1:Import pickle module.

STEP 2:Initialize an empty dictionary (sdata) and an empty list (slist).

STEP 3:Get number of students as input from the user and assign it to variable ‘totals’.

STEP 4:Create a for loop in the range of totals .In the loop ,get roll number and name as input
from user and assign the values to the sdata dictionary’s keys(Rollno and Name).

STEP 5:Append s data to slist and assign an empty dictionary to sdata.

STEP 6:Open the ‘text2.dat’ file in write mode and dump the slist data in it and then close the
file.

STEP 7:Reopen the same file in read mode and load its data into ‘slist‘.

STEP 8:Get the roll no. of the student to be searched from the user and assign it to ‘b’.

STEP 9:Set ‘y’ as false.

STEP 10:Iterate over the ’slist’ and check if ‘b’ is present as a value.

STEP 11:If present, print the name of the student. If not, print ‘data not found’.

STEP 12:Save and execute the programs.


14. CREATE A BINARY FILE WITH NAME & ROLL NUMBER,
SEARCH FOR A GIVEN ROLL NUMBER AND DISPLAY
NAME, IF NOT FOUND DISPLAY A MESSAGE

SOURCE CODE:
import pickle

sdata={}

slist=[]

totals = int(input('Enter the Number of students:'))

for i in range(totals):

rollno= int(input('Enter Rollno:'))

name= input('Enter name:')

sdata['Rollno']= rollno

sdata['Name']= name

slist.append(sdata)

sdata={}

a= open('text2.dat','wb')

pickle.dump(slist,a)

a.close()

x=open('text2.dat','rb')

slist= pickle.load(x)

b=int(input('Enter the rollno of students to be searched:'))

y=False
for text2 in slist:

if text2['Rollno']==b:

y=True

print(text2['Name'],'Found in file')

if not y:

print('Data of students not found')


14 .CREATE A BINARY FILE USING ROLL NUMBER

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
CREATE A BINARY FILE WITH ROLL
EX.NO: 15 NUMBER , NAME & MARKS, INPUT A
DATE: ROLL NUMBER & UPDATE THE
MARK

AIM:

To create a binary file with name and roll number, search for a given roll
number and display name , if not found display the message

ALGORITHM:

STEP 1 : Import the pickle module and create an empty dictionary sdata={} and
slist=[] .

STEP 2 : Get the imput from the user to enter the number of students.

STEP 3 : Create a for loop in the range of numbers of students.

STEP 4 : Get roll no and name as input from the user and insert each of these data
as values into sdata.

STEP 5 : Append the data in sdata in slist and assign an empty dictionary to sdata.

STEP 6 : Open a binary file TEXT2.dat in read mode and use the load() function in
pickle module to write slist onto the file.

STEP 7 : Get roll no. to be searched as the input from the user and assign it to a
variable b.

STEP 8 : Initialize a flag variable as False.

STEP 9 : Get roll no. as input from user and assign it to variable rollno and open
‘TEXT3.dat’ in read and write mode.

STEP 10 : In try block, in a while loop, assign the position of pointer to variable
pos using tell() function.
STEP 11 : In sdata , store all data in file handle “a” , check if the entered roll no is
equal to the value of roll no in sdata and if true , ask for marks to be updated as
input from user and assign it to sdata*“Marks”+.

STEP 12 : Place the pointer in ‘pos’ using seek() function and write sdata onto file
‘a’. Change found to true.

STEP 13 : In except block , for EOF error, if roll no is not found , display ‘Roll
number not found’ and if found display ‘students mark updated successfully’.

STEP14 : Save and execute the program.


15. CREATE A BINARY FILE WITH ROLL NUMBER,
NAME & MARKS, INPUT A ROLL NUMBER &
UPDATE THE MARKS

SOURCE CODE:
import pickle

sdata={}

totals=int(input("ENTER NUMBER OF STUDENTS:"))

a=open("TEXT3.dat","wb")

for i in range(totals):

sdata["Roll no"]=int(input("Enter roll no:"))

sdata["Name"]=input("Enter Name:")

sdata["Marks"]=float(input("Enter mark:"))

pickle.dump(sdata,a)

sdata={}

a.close

#UPDATE MAEKS

found=False

rollno=int(input("ENTER ROLL NUMBER"))

a=open("TEXT3.dat","rb+")
try:

while True:

pos=a.tell()

sdata=pickle.load(a)

if(sdata["Roll no"]==rollno):

sdata["Marks"]=float(input("Enter new mark:"))

print(sdata)

a.seek(pos)

pickle.dump(sdata,a)

found=True

except EOFError:

if found==False:

print("Roll Number Not Found")

else:

print("Student Mark Updated Successfully")

a.close()
15 .TO CREATE A BINARY FILE

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 16 TO REMOVE ALL THE LINES THAT
CONTAIN THE LETTER ‘A’ IN A FILE
DATE:
AND WRITE IT TO ANOTHER FILE

AIM:

To remove all the lines that contain the letter ‘a’ in a file and write it to another
file.

ALGORITHM:

STEP 1: Open a text file by creating a connection and specifying the modes and
the text file name (<filehandle>=file).

STEP 2: Initiate an identifier to store the lines read by the readlines( ) function
and close the file using close ( ) function.

STEP 3: Open another text file with the file object as file 1 and create connection
to open a text file named “MODTEXT1.txt” in write mode and again open the first
file also in write mode.

STEP 4: Create a for loop that iterates through the lines read in the first file and
use a if condition to check whether the letter “a” is present in read lines of the file
.If “a” is found in the read lines write those into another file using write( ) function
else write it in the same file itself.

STEP 5: After the completion of iterations by the for loop ,the print statement
prints the following(“Lines that contain a character are removed from
TEXT1),(“Lines that contain a character are added in MODTEXT1”)

STEP 6: Save and execute the program to get the output.


16. TO REMOVE ALL THE LINES THAT CONTAINS
THE LETTER ‘A’ IN A FILE AND WRITE IT TO
ANOTHER TABLE

SOURCE CODE:

file=open("TEXT1.txt","r+")

lines=file.readlines()

file.close()

file1=open("MODTEXT1.txt","w")

file=open("TEXT1.txt","w")

for line in lines:

if "a" in line:

file1.write(line)

else:

file.write(line)

print("Lines That Contain A Character Are Removed From TEXT1")

print("Lines That Contain A Character Are Removed From MODTEXT1")

file.close()

file1.close()
16 .REMOVE “A” IN FILE

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 17 READ AND DISPLAY FILE CONTENT
LINE BY LINE WITH EACH WORD
DATE:
SEPARATED BY #

AIM:

To read and display file content line by line with each word separated by #

ALGORITHM:

STEP 1: Open a text file in read mode with the file handling “a”.

STEP 2: Create an identifier to store the read lines by using the readlines()
method.

STEP 3: Create a for loop to iterate through the lines read from the file (TEXT.txt).
Use then split() function to split the lines read from the file. Create another
nested for loop which prints (y+’#’,end=” ”),(“ ”).

STEP 4: Save and execute the programs.


17. READ AND DISPLAY FILE CONTENT LINE BY
LINE WITH EACH WORD SEPERATED BY #

SOURCE CODE:

a=open("TEXT.txt","r")

lines=a.readlines()

for line in lines:

x=line.split()

for y in x:

print(y+'#',end=" ")

print(" ")

input()
17 .Separating words by “#”

Output :

RESULT :
Thus , the above python code was typed and executed successfully
READ A LINE AND COUNT THE
EX.NO: 18
NUMBER OF UPPERCASE
DATE: LOWERCASE ALPHABETS AND
DIGITS

AIM:

To read a line and count the number of uppercase, lowercase, alphabets and
digits.

ALGORITHM:

STEP 1: Get a sentence as input from user and assign to variable ‘line’.

STEP 2: Initialize 4 variables lowercount, uppercount, alphacount, digitcount as 0

STEP 3: Iterate the line character by character using the for loop

STEP 4: In the loop, use if and elif conditions to check if the character is alphabet,
number, lower case letter or upper case letter using isalpha( ) ,isdigit( ) ,islower()
and isupper( ) functions.

STEP 5: If True, increment the lowercount ,uppercount, alphacount, digitcount


by 1.

STEP 6: After all iterations, display the number of upper case letters, lower case
letters , alphabets and numbers in separate statements.

STEP 7: Save and execute the programs.


18. READ A LINE AND COUNT THE NUMBR OF
UPPERCASE, LOWERCASE, ALPHABETS AND
DIGITS

SOURCE CODE:

line=input("Enter a line:")

lowercount = uppercount= 0

digitcount = alphacount= 0

for a in line:

if a.islower():

lowercount += 1

elif a.isupper():

uppercount += 1

elif a.isdigit():

digitcount += 1

if a.isalpha():

alphacount += 1

print("number of upper case letters:", uppercount)

print("number of lower case letters:" ,lowercount)

print("number of alphabets:", alphacount)

print("number of digits:", digitcount)


18 .COUNT THE NUMBER OF UPPERCASE , LOWER
CASE , ALPHABETS AND DIGITS

OUTPUT :

RESULT :
Thus , the above python code was typed and executed successfully
EX.NO: 19
STACK OPERATIONS
DATE:

AIM:

To implement the stack operation using a list data structure

ALGORITHM:

STEP 1: Create an empty list “Stack” and specify top=”None”.

STEP 2: Initiate a while loop. If the condition gets true print the following :

STACK OPERATIONS

1. Push
2. Pop
3. Peek
4. Display
5. Exit

STEP 3: Initiate a variable “ch” and get the choice from the user (1 to 5).

STEP 4: If ch==1 , initiate another variable item and get the item from the user.
The push function is executed. The item is appended in the stack and top is
updated by top=len(stack)-1.

STEP 5: If ch==2, assign the variable item to pop function and the pop function is
executed. If the function returns “underflow” print that the stack is empty ,or
otherwise the popped is returned with the top updated.

STEP 6: If ch==3, assign the variable item to the peek function and the peek
function gets executed. Then the peek function gets executed and if this returns
“underflow “ print that the stack is empty or otherwise print the item returned
from the function to be top most element in the stack. In the function the top
gets updated.

STEP 7: If ch==4, the display functions get executed and in the function if the
stack is empty it displays as it is and if there are elements in the stack top gets
updated and the top of the stack is printed for displaying . Then using the for loop
elements of the stack are displayed.

STEP 8: If ch==5, the while loop is broken using break keyword. This loop gets into
the else condition while loop prints. “The given choice is invalid” if the condition
break.
19. STACK OPERATION

SOURCE CODE:
def isempty(stack):

if stack==[]:

return True

else:

return False

def push(satck,item):

stack.append(item)

top=len(stack)-1

def pop(stack):

if isempty(stack):

return "Underflow!"

else:

item=stack.pop( )

if len(stack)==0:

top=None

else:

top=len(stack)-1

return item

def peek(stack):

if isempty(stack):
return "Underflow!"

else:

top=len(stack)-1

return stack[top]

def display(stack):

if isempty(stack):

return "Underflow!"

else:

top=len(stack)-1

print(stack[top],"-->top")

for i in range(top-1,-1,-1):

print(stack[i])

stack=[]

top=None

while True:

print("STACK OPERATIONS")

print("1.push")

print("2.pop")

print("3.peek")

print("4.display")

print("5.exit")

ch=int(input("Enter your choice between 1-5:"))

if ch==1:

item= int(input("Enter the item"))


push(stack,item)

elif ch==2 :

item= pop(stack)

if len(stack)==0:

print("stack empty underflow")

else:

print("the popped item is",item)

elif ch==3:

item=peek(stack)

if len(stack)==0:

print ("stack empty underflow")

else :

print ("the topmosst item is",item)

elif ch==4 :

display(stack)

elif ch==5 :

break

else :

print ("invalid choice!")


19 .STACK OPERATIONS

OUTPUT :
20. INTEGRATE PYTHON WITH SQL:
FETCHING RECORDS FROM TABLE
AIM:
To integrate SQL with python by impoting the MySQL module and extracting data from the
result set.

SOURCE CODE:
import mysql.connector as s

mycon=s.connect(host='localhost',user='root',passwd='1234',database='school')

if mycon.is_connected()==False:

print("Enter connecting to MySQL database")

cursor=mycon.cursor()

cursor.execute("Select * from graduate")

data=cursor.fetchall()

count=cursor.rowcount

for row in data:

print(row)

mycon.close()

RESULT:
Thus the given program executed successfully.
OUTPUT:
21.INTEGRATE PYTHON WITH SQL:
COUNTING RECORDS FROM TABLE
AIM:
To integrate SQL with python by importing the MySQL module and extracting data from
the result set.

SOURCE CODE:
import mysql.connector as s

mycon=s.connect(host='localhost',user='root',passwd='1234',database='school')

if mycon.is_connected()==False:

print("Error connecting to MySQL database")

cursor=mycon.cursor()

cursor.execute("Select* from graduate")

data=cursor.fetchone()

count=cursor.rowcount

print("Total number of rows retrieved from resultset:", count)

data=cursor.fetchone()

count=cursor.rowcount

print("Tota number of rows retrieved frm the result set:", count)

data=cursor.fetchmany(3)

count=cursor.rowcount

print("Total number of rows retrieved from resultset:", count)

RESULT:
Thus the given program executed successfully.
OUTPUT
22. INTEGRATE SQL WITH PYTHON:
SEARCHING A RECORD FROM TABLE
AIM:
To integrate SQL with python by importing the MySQL module and extracting 1
data from the result set.

SOURCE CODE:
import mysql.connector as s

mycon=s.connect(host='localhost',user='root',passwd='1234',database='school')

if mycon.is_connected():

print("Interface is successfully established")

s_no=int(input("Enter num: "))

cursor=mycon.cursor()

cursor.execute("Select * from graduate")

allrow=cursor.fetchall()

for row in allrow:

if row[0]==s_no:

print(row)

mycon.commit()

mycon.close()

RESULT:
Thus the given program executed successfully.
OUTPUT:
23. INTEGRATE SQL WITH PYTHON:
DELETING A RECORD FROM TABLE
AIM:
To integrate SQL with Python by importing the MySQL module to search a student using
rollno and delete the record.

SOURCE CODE:
import mysql.connector as s

mycon=s.connect(host="localhost",user="root",passwd="1234",database="school")

if mycon.is_connected():

print("INTERFACE IS SUCCESSFULLY ESTABLISHED")

sno=int(input("enter the number"))

mycursor=mycon.cursor()

mycursor.execute("select * from graduate")

allrow=mycursor.fetchall()

for row in allrow:

if row[0]==sno:

mycursor.execute("delete from graduate where sno={}".format(sno))

mycursor.execute("select * from graduate")

data=mycursor.fetchall()

for i in data:

print(i)

mycon.commit()

mycon.close()

RESULT:
Thus the given program executed successfully,
OUTPUT:
24. STATIONARY AND CONSUMER
AIM:

To create two tables for STATIONARY and consumer and execute the given
commands using SQL.

TABLE:STATIONARY

S_ID STATIONARY COMPANY PRICE


Name
DP01 Dot Pen Figo 10
PL02 Pencil Fabercastel 6
ER05 Eraser Pentonic 7
PL01 Pencil Natraj 5
GP02 Gel pen apsara 15

TABLE: CONSUMER

C_ID ConsumerName Address S_ID


01 Vijay Delhi PL01
06 Surya Mumbai GP02
12 Kamal Delhi DP01
15 Natasha Delhi PL02
16 Peter Bangalore PL01

i)To display the details of those Consumers whose Address in Delhi.


ii)To display the details of STATTIONARY WHOSE Price is in the range of 8 to
15(Both values included)
iii)To display the ConsumerName , Address from table Consumer and Company
and Price from table Stationary with their corresponding matching S_ID
iv)To increase the Price of all STATIONARY by 2
v)To display distinct Company from STATIONERY.
OUTPUT:

i) Select * from consumer where address=”delhi”;

ii) Select * from stationary where price between 8 and15;

iii) Select consumer_name, address, company, price from stationary,


consumer where stationary.s_id=consumer.s_id;

iv) Update stationary set price =price+2;


Select * from stationary;
v) Select distinct(company) from stationary;
25. ITEM AND TRADERS
AIM:

To create two tables for item and traders and execute the given commands
using SQL.

TABLE: ITEM
CODE INAME QTY PRICE COMPANCY TCODE

1001 DIGITAL PAD 121 120 11000 XENTIA T01

1006 LED SCREEN 40 70 38000 SANTORA T02

1004 CAR GPS SYSTEM 50 2150 GEOKNOW T01

1003 DIGITAL CAMERA 12X 160 8000 DIGICLICK T02

1005 PEN DRIVE 600 1200 STOREHOME T03

TABLE: TRADERS
TCODE TNAME CITY
T01 ELECTRONICS SALES MUMBAI
T03 BUSY STORE CORP DELHI
T02 DISP HOUSE INC CHENNAI

a) To display the details of all the items in ascending order of item names(i.e IName)
b) To display item name and price of all those items ,whose price is in the range of 10000
and 22000(both values inclusive)
c) To display the number of items, which are traded by each trader .The expected output of
this query should be
T01 2
TO2 2
TO3 1
d) To display the price , item name(i.e IName) and quantity (i.eQty) of those items which
have quantity more than 150.
e) To display the names of those traders, who are either from DELHI or from MUMBAI
OUTPUT:
1.

2.

3.
4.

5.
26. DOCTOR AND SALARY
AIM:
To create to tables for doctor and salary and execute the given commands using SQL.

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 K George Medicine M 9
105 Johnson Orthopedic F 10
117 Lucy Ent F 3
111 Bill Medicine F 12
130 Morphy Orthopedic M 15

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
130 21700 2600 300

i)Display NAME of all doctors who are in “MEDICINE” having more than 10 years experience
from table DOCTOR

ii)Display the average salary of all doctors working in “ENT” department using the tables
DOCTOR and SALARY.(Salary=BASIC+ALLOWANCES)

iii)Display minimum ALLOWANCE of female doctors.

iv)Display DOCTOR.ID,NAME from the table DOCTOR and BASIC,ALLOWANCE from the table
SALARY with their corresponding matching id.

v)To display distinct department from the table doctor.


RESULT:
Thus, the given queries are executed successfully
OUTPUT:
1.

2.

3.

4.
5.

You might also like