Xii - Practicals 24-25

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

EVERWIN VIDHYASHRAM SR. SEC.

SCHOOL

SSCE COMPUTER SCIENCE

PRACTICAL LAB MANUAL XII -[CBSE]

SUBJECT CODE : 083


LIST OF PROGRAMS:

1. PROGRAM TO FIND A FACTORIAL NUMBER.


2. PROGRAM TO COUNT UPPER AND LOWER CASE LETTERS.
3. PROGRAM THAT MULTIPLIES TWO INTEGER NUMBERS BY USING
REPEATED ADDITION.
4. CREATING A MENU DRIVEN PROGRAM TO FIND AREA OF CIRCLE,
RECTANGLE AND TRIANGLE.
5. PROGRAM TO ADD ONE TO ALL THE EVEN NUMBERS AND SUBTRACT
ONE FOR ALL ODD NUMBERS IN A GIVEN LIST USING FUNCTION
EOREPLACE() AND PRINT THE MODIFIED LIST.
6. PROGRAM TO SIMULATE THE DICE USING RANDOM FUNCTION.
7. PROGRAM TO SEARCH ANY WORD IN GIVEN STRING/SENTENCE.

8. PYTHON PROGRAM TO READ A TEXT FILE LINE BY LINE AND DISPLAY


EACH WORD SEPARATED BY ‘#’.

9. PROGRAM TO COUNT THE NUMBER OF VOWELS AND CONSONANTS IN A


TEXT FILE.

10. PROGRAM TO COPY ALL THE LINES THAT CONTAIN THE


CHARACTER ‘A’ OR ‘a’ IN A FILE AND WRITE IT TO ANOTHER FILE.

11. PROGRAM TO COUNT THE NUMBER OF LINES IN A TEXT FILE


‘ANSWER.TXT’ WHICH IS STARTING WITH AN ALPHABET ‘M’ OR ‘m’.

12. PROGRAM TO CREATE A BINARY FILE AND SEARCH FOR A RECORD.

13. PROGRAM TO CREATE CSV FILE AND COUNT NUMBER OF RECORDS.


14. WRITE A PROGRAM TO HANDLE EXCEPTION.

15. WRITE A PROGRAM USING PYTHON TO PERFORM LINEAR


SEARCHING.

16. PROGRAM TO IMPLEMENT STACK OPERATION.

17. SQL QUERIES - DDL COMMANDS.

18. DML COMMANDS.

19. SQL QUERIES - ORDER BY CLAUSE.

20. SQL QUERIES - GROUP BY CLAUSE.

21. SQL- COMPANY AND CUSTOMER.

22. PROGRAMS TO FETCH ALL THE RECORDS FROM STUDENT TABLE.

23. PROGRAMS TO FETCH RECORDS FROM STUDENT TABLE ON A GIVEN


CONDITION.

24. PROGRAMS TO INSERT RECORDS INTO TABLE.

25. PROGRAMS TO UPDATE RECORDS IN A TABLE.


XII C.S LAB Programs code-083

PROGRAM NO: 1

PROGRAM TO FIND A FACTORIAL NUMBER.


AIM:

To write a Python program to calculate factorial of a number using function.

PROGRAM CODE:

# Program to find factorial of a number

def factorial(n):
f=1
for i in range(1,n+1):
f=f*i
return f
n=int(input("Input a number to compute the factorial : "))
print("Factorial of ",n,"is:",factorial(n))

OUTPUT:
PROGRAM NO: 2

PROGRAM TO COUNT UPPER AND LOWER CASE LETTERS.


AIM:

To write a Python program to find the number of upper case and lower case
letters in a string which is passed as an argument to the function.

PROGRAM CODE:

#Program to count upper and lower case letters.

def string_test(s):
up=0
low=0
for i in s:
if i.isupper():
up=up+1
if i.islower():
low=low+1
print("original string is:",s)
print("no.of upper case character:",up)
print("no.of lower case character:",low)
string=input("enter a string:")
string_test(string)
OUTPUT:
PROGRAM NO: 3

Write a program that multiplies two integer numbers without using the * operator,
using repeated addition.

AIM:

To write a Python program that multiplies two integer numbers without using

the * operator, using repeated addition.

PROGRAM

n1 = int(input("Enter first number :"))


n2 = int(input("Enter second number :"))
product = 0
count = n1
while count > 0:
count = count - 1
product = product + n2
print("The product of", n1, "and", n2, "is", product)

OUTPUT:
PROGRAM NO : 4

CREATING A MENU DRIVEN PROGRAM TO FIND AREA OF CIRCLE,

RECTANGLE AND TRIANGLE

AIM:

To write a menu driven Python Program to find Area of Circle, Rectangle a Triangle
using function.

PROGRAM CODE :

def Circle(r):
Area = 3.141*(r**2)
print(“The Area of circle is : “,Area)
def Rectangle(L,B):
R=L*B
print(“The Area of rectangle is : “,R)
def Triangle(B, H):
R=0.5*B*H
print (“The Area of triangle is : “,R)
print (“1.Area of Circle”)
print (“2.Area of Rectangle”)
print (“3.Area of Triangle”)
ch=int(input(“Enter your choice:”))
if ch==1:
r = float(input(“Enter the radius value : “))
Circle(r)
elif ch==2:
L=int(input(“Enter the Length of the Rectangle : “))
B=int(input(“Enter the Breadth of the Rectangle : “))
Rectangle(L,B)
elif ch==3:
B=int(input(“Enter the Base of the triangle:”))
H=int(input(“Enter the height of the triangle:”))
Triangle(B, H)
else:
print (“invalid option”)
PROGRAM NO:5

Program to add one to all the even numbers and subtract one for all
odd numbers in a given list using the function EOReplace() and print
the modified list
AIM:

To write a program to add number one to all the even numbers and
subtract number one for all odd numbers in a given list using the
function EOReplace() and print the modified list
PROGRAM CODE:

def EOReplace(L):
newList = [ ]
for i in L:
if i % 2 ==0:
newList.append(i +1)
else:
newList.append(i -1)
return newList
L=[10, 20, 30, 40, 35, 55]
modified = EOReplace(L)
print(modified)

OUTPUT:
PROGRAM NO:6

PROGRAM TO SIMULATE THE DICE


AIM:

To write a Python program to simulate the dice using random module.

PROGRAM CODE:

#Program to simulate the dice

import random
import time
print("Press CTRL+C to stop the dice!!!")
play='y'
while play=='y':
try:
while True:
for i in range(1):
print()
n = random.randint(1,6)
print(n)
time.sleep(0.5)
except KeyboardInterrupt:
print("\nYour Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
OUTPUT:
PROGRAM NO:7

Program to Search any word in a given string/sentence.

AIM:

To write a Python program to search any word in given string/sentence.

PROGRAM CODE:

def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input(“Enter any sentence :”)
word = input(“Enter word to search in sentence :”)
count = countWord(str1,word)
if count==0:
print(“## Sorry! “,word,” not present “)
else:
print(“## “,word,” occurs “,count,” times ## “)

Output:-
PROGRAM NO:8

program to read a text file line by line and display each word separated by a ‘#’

AIM:

To Write a Python program to read a text file line by line and display each word
separated by a ‘#’

PROGRAM CODE

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:
PROGRAM NO:9

PROGRAM TO COUNT THE NUMBER OF VOWELS AND CONSONANTS IN A TEXT


FILE.

AIM:

To write a Python program to count number of vowels and consonants in a


text file.

PROGRAM CODE:

# Program to count number of vowels and consonants in a text file

myfile=open("E:\\TextFile\\Poem.txt","r")
vowels="aeiouAEIOU"
count1=0
count2=0
data=myfile.read()
for i in data:
if i in vowels:
count1=count1+1
else:
count2=count2+1
print("Number of Vowels:",count1)
print("Number of Consonants:",count2)

OUTPUT:

Number of Vowels: 4

Number of Consonants: 21
PROGRAM NO:10

COPYING LINES IN A FILE Copy all the lines that contain the character `a' in a file
and write it to another file.

AIM:

To write a python program to Copy all the lines that contain the character `a' in a
file and write it to another file.

PROGRAM:

Fin=open(“xiics2.txt”,”r”)
Fout=open(“xiics4.txt”,”w”)
for line in fin:
word=line.split( )
for i in word:
for letter in i:
if letter==’a’ or letter==’A’:
Fout.write(line)
Fin.close( )
Fout.close( )
OUTPUT:
xiics2.txt
We are aware if ATM cards that are used in ATM machines.
xiics4.txt
We are aware if ATM cards that are used in ATM machines.
RESULT:

The given program is executed successfully and the result is verified.


PROGRAM NO:11
WRITE A FUNCTION IN PYTHON PROGRAM TO COUNT THE NUMBER OF LINES
IN A TEXT FILE ‘ANSWER.TXT’ WHICH IS STARTING WITH AN ALPHABET ‘M’ OR
‘m’.
AIM:
To write a function in python program to count the number of lines in a text file
‘ANSWER.TXT’ which is starting with an alphabet ‘M’ or ‘m’.
PROGRAM:
def COUNTLINES():
File = open(‘ANSWER.TXT’,’r’)
lines = File.readlines()
Count = 0
for w in lines:
if w[0] == ‘M’ or w[0] == ‘m’:
Count = Count + 1
print(“Total lines started with M or m :”, Count)
File.close()
COUNTLINES()

If the ANSWER.TXT contents are as follows:


“My first book was me and my family.
It gave me chance to be known to the world.”

OUTPUT:
Total lines started with M or m : 1
PROGRAM NO:12

Write a program to Create a binary file with name and roll number using
dictionary. And search for a record with roll number as 34 or 36, if found display
the record.

AIM:
To write a program to Create a binary file with name and roll number
using dictionary. And search for a record with roll number as 34 or 36, if
found display the record.
PROGRAM

#Create a binary file with name and roll number


import pickle
file=open(“StudDtl.dat”,”wb”)
stud_data={}
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: ")
pickle.dump(stud_data,file)
print("Data added successfully")
file.close()
#search for a record with roll number as 34 or 36, if found display the
record.
import pickle
file=open("StudDtl.dat","rb")
stud_data={}
S_k=[34,36]
found = False
try:
while True:
stud_data=pickle.load(file)
if stud_data["roll_no"] in S_k:
found=True
print(stud_data["name"],"found in file.")
except:
if (found==False):
print("No student data found. please try again")
file.close()

output:-
#create
Enter no of students: 2
Enter name: Jai
Enter roll no: 36
Enter name: vignesh
Enter roll no: 35
Data added successfully
#Search
Jai found in file
PROGRAM NO: 13

PROGRAM TO CREATE CSV FILE.


AIM:

To write a Python program to create csv file to store information about


some products.
PROGRAM CODE:

# Program to create a CSV file to store product details.

import csv
myfile=open('Product.csv','w',newline='')
prod_writer=csv.writer(myfile)
prod_writer.writerow(['CODE','NAME','PRICE'])
for i in range(2):
print("Product", i+1)
code=int(input("Enter Product code:"))
name=input("Enter Product Name:")
price=float(input("Enter Price:"))
prod=[code,name,price]
prod_writer.writerow(prod)
print("File created successfully!")
print('###############')
myfile.close()

myfile = open(‘Product.csv’,’r’)
prod_reader=csv.reader(myfile)
Data = list(prod_reader)
Count= len(Data)
print(“No of records:”, Count)
myfile.close()
Output :

Product 1
Enter Product code:104
Enter Product Name: Pen
Enter Price:200
Product 2
Enter Product code:405
Enter Product Name: Marker
Enter Price:50
File created successfully!
###############
No of records: 2
PROGRAM NO: 14

PROGRAM TO HANDLE EXCEPTIONS BY USING TRY AND EXCEPT BLOCKS

AIM:

To write a Python program to Handle (Predefined) Exceptions by using try

and except blocks.

PROGRAM CODE:

print (“Handling exception using try…except…else…finally”)


try:
numerator = 50
denom= int(input(“Enter the denominator: “))
quotient = (numerator/denom)
print (“Division performed successfully”)
except ZeroDivisionError:
print (“Denominator as ZERO is not allowed”)
except ValueError:
print (“Only INTEGERS should be entered”)
else:
print (“The result of division operation is “, quotient)
finally:
print (“OVER AND OUT”)
OUTPUT
PROGRAM NO: 15

Write a program using python to perform linear searching

AIM:

To write a Python program to perform linear searching in an array

PROGRAM CODE:

def linear_search(lst, size, key):


flag = 0
for i in range(size):
if lst[i] == key:
flag = 1
pos = I + 1
break
if flag == 1:
print(“Number found at”, pos, “position”)
else:
print(“Number not found”)
#main()
size = int(input(“Enter the size or list : “))
lst = []
for i in range(size):
val = int(input(“Enter number : “))
lst.append(val)
key = int(input(“Enter number to search : “))
linear_search(lst, size, key)
output:-
PROGRAM NO: 16

PROGRAM TO IMPLEMENT STACK OPERATION.


AIM :
To write a Python program to implement stack operations.

PROGRAM:
def isEmpty(Emp):
if Emp==[]:
return True;
else:
return False;
def Push(Emp,Name):
Emp.append(Name)
top=len(Emp)-1
def Pop(Emp):
if isEmpty(Emp):
return "Underflow"
else:
Name=Emp.pop()
if len(Emp)==0:
top=None
else:
top=len(Emp)-1
return Name
def Peek(Emp):
if isEmpty(Emp):
return "Underflow"
else:
top=len(Emp)-1
return Emp[top]

def Display(Emp):
if isEmpty(Emp):
print ("Stack Underflow")
else:
top=len(Emp)-1
print(Emp[top],"<-Top")
for a in range(top-1,-1,-1):
print(Emp[a])
# main segment
Stack=[]
top=None
while True:
print("----------------------")
print("Stack Operations")
print("----------------------")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
name=input("Enter Name of the Employee:")
Push(Stack,name)
elif ch==2:
name=Pop(Stack)
if name=="Underflow":
print("Stack Underflow!")
else:
print("Deleted Name is:",name)
elif ch==3:
name=Peek(Stack)
if name=="Underflow":
print("Stack Underflow")
else:
print("Topmost Name in Stack is:",name)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid Choice!")
OUTPUT:

Stack Operations
-----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):1
Enter Name of the Employee: Kumar
-----------------------
Stack Operations
-----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit

Enter your choice(1-5):1


Enter Name of the Employee: Arun
----------------------
Stack Operations
----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):4
Arun <-Top
Kumar
-----------------------
Stack Operations
-----------------------
1.Push
2.Pop
3.Peek

4.Display
5.Exit
Enter your choice(1-5):3
Topmost Name in Stack is: Arun
-----------------------
Stack Operations
-----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):2
Deleted Name is: Arun
----------------------
Stack Operations
----------------------
1.Push
2.Pop

3.Peek
4.Display
5.Exit
Enter your choice(1-5):4
Kumar <-Top
----------------------
Stack Operations
----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):2
Deleted Name is: Kumar

----------------------
Stack Operations
----------------------
1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):2
Stack Underflow!
-----------------------
Stack Operations
-----------------------

1.Push
2.Pop
3.Peek
4.Display
5.Exit
Enter your choice(1-5):5
###SQL QUERIES ###

17. SQL QUERIES - DDL COMMANDS.

DDL Commands:
• Create

• Alter

• Drop
18. DML Commands

• Insert
• Update
• Delete
DML Commands
19.SQL QUERIES - ORDER BY CLAUSE.
20. SQL QUERIES - GROUP BY CLAUSE.
21. COMPANY AND CUSTOMER

AIM:
To create two tables for company and customer and execute the given commands using SQL.

TABLE:COMPANY

TABLE:CUSTOMER

1. To display those company name which are having price less than 30000.

2. To display the name of the companies in reverse alphabetical order.

3. To increase the price by 1000 for those customer whose name starts with ‘S’

4. To add one more column total price with decimal (10,2) to the table customer

5. To display the details of company where product name as mobile.


CREATE TABLE COMPANY(cid int(3), name varchar(15), city varchar(10), productname

varchar(15));

INSERT INTO COMPANY VALUES(111,‘SONA’,‘DELHI’,‘TV’);


CREATE TABLE CUSTOMER(custid int(3), name varchar(15), price int(10), qty int(3) ,cid

int(3));

INSERT INTO CUSTOMER VALUES(101, ‘ROHAN SHARMA’, 70000,20,222);

RESULT:

Thus the given program executed successful

OUTPUT:

1. select company.name from company, costumer where


company.cid=customer. cid and price <30000;

NAME
NEHA SONI
2. select name from company order by name desc;

NAME
SONY
ONIDA
NOKIA
DELL
BLACKBERRY
3. Update customer set price = price + 1000 where name like ‘s%’; select * from
customer;

CUSTID NAME PRICE QTY CID


101 ROHANSHARMA 70000 20 222
102 DEEPAKKUMAR 50000 10 666
103 MOHANKUMAR 30000 5 111
104 SAHILBANSAL 36000 3 333
105 NEHASONI 25000 7 444
106 SONAAGARWAL 21000 5 333
107 ARUNSINGH 50000 15 666

4. Alter table customer add totalprice

decimal(10,2); Select*from customer;

CUSTID NAME PRICE QTY CID TOTALPRICE


101 ROHANSHARMA 70000 20 222 NULL
102 DEEPAKKUMAR 50000 10 666 NULL
103 MOHANKUMAR 30000 5 111 NULL
104 SAHILBANSAL 36000 3 333 NULL
105 NEHASONI 25000 7 444 NULL
106 SONAAGARWAL 21000 5 333 NULL
107 ARUNSINGH 50000 15 666 NULL
5. select*from company where product name=’mobile’;

CID NAME CITY PRODUCTNAME


222 NOKIA MUMBAI MOBILE
444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE
22. PROGRAMS T0 FETCH ALL THE RECORDS FROM STUDENT TABLE.
AIM :

To write a Python program to fetch all the records from the Student
Table.

PROGRAM ALGORITHM:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Fetch all the records from the table using fetchall().
6. Traverse the result set using for loop and print the records.
7. Close the connection using close().
8. Stop.

PROGRAM CODE :
# Program to fetch all the records from Student table
import mysql.connector as sqltor
con=sqltor.connect(host="localhost",user="root",passwd="ss123",database="s
ps")
if con.is_connected==False:
print('Error')
cursor=con.cursor()
cursor.execute("select * from Student")
data=cursor.fetchall()
count=cursor.rowcount
print("No.Rows:",count)
for row in data:
print(row)
con.close()
SAMPLE OUTPUT :
No.Rows: 5
(101, 'Arun', 12, 'A', 450, 90)
(102, 'David', 12, 'B', 400, 80)
(103, 'Anand', 12, 'B', 350, 70)
(104, 'Reena', 12, 'A', 380, 76)
(105, 'Neha', 12, 'A', 420, 84)
23. PROGRAMS T0 FETCH RECORDS FROM STUDENT TABLE ON A
GIVEN CONDITION

AIM :

To write a Python program to fetch the records from the Student Table

which satisfies the given condition.

PROGRAM ALGORITHM:

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute SQL query with string formatting.
6. Fetch all the records from the table using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
PROGRAM CODE :

# Program to fetch records which satisfies the given condition.

import mysql.connector as sqltor

con=sqltor.connect(host="localhost",user="root",passwd="ss123",database="s
ps")

if con.is_connected==False:

print('Error')

cur=con.cursor()

cur.execute("select * from student where percentage>={}".format(80))

data=cur.fetchall()

count=cur.rowcount

print("No.Rows:",count)

for row in data:

print(row)

con.close()

SAMPLE OUTPUT :

No.Rows: 3

(101, 'Arun', 12, 'A', 450, 90)

(102, 'David', 12, 'B', 400, 80)

(105, 'Neha', 12, 'A', 420, 84)


24. PROGRAMS T0 INSERT RECORDS INTO TABLE.

AIM :

To write a Python program to insert new record into Student Table.

PROGRAM ALGORITHM :

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit() to save
the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
PROGRAM CODE :

# Program to insert new record into table.

import mysql.connector as sqltor


con=sqltor.connect(host="localhost",user="root",passwd="ss123",database="s
ps")
if con.is_connected==False:
print('Error')
cur=con.cursor()
query="insert into student values({},'{}',{},'{}',{},{})".format(106,'Raj',12,'A',430,86)
cur.execute(query)
con.commit()
print("Record Inserted")
cur.execute("Select * from Student")
print("Table after insertion")
data=cur.fetchall()
for row in data:
print(row)
con.close()
Output :

Record Inserted

Table after insertion

(101, 'Arun', 12, 'A', 450, 90)

(102, 'David', 12, 'B', 400, 80)

(103, 'Anand', 12, 'B', 350, 70)

(104, 'Reena', 12, 'A', 380, 76)

(105, 'Neha', 12, 'A', 420, 84)

(106, 'Raj', 12, 'A', 430, 86)


25. PROGRAMS T0 UPDATE RECORDS IN A TABLE.

AIM :

To write a Python program to update record in a table.

PROGRAM ALGORITHM :

1. Start.
2. Import mysql.connector module.
3. Establish connection using connect().
4. Create Cursor instance using cursor().
5. Execute insert command with string formatting and apply commit()
to save the changes permanently.
6. Execute select query and fetch all the records using fetchall().
7. Traverse the result set using for loop and print the records.
8. Close the connection using close().
9. Stop.
PROGRAM CODE :

# Program to update record in a table.

import mysql.connector as sql


con=sql.connect(host="localhost",user="root",passwd="ss123",database=
"sps")
if con.is_connected==False:
print('Error')
cur=con.cursor()
query="update student set section='{}' where name='{}'".format('B','Neha')
cur.execute(query)
con.commit()
print("Record Updated")
cur.execute("Select * from Student")
print("Table after Updation")
data=cur.fetchall()
for row in data:
print(row)
con.close()
Output :

Record Updated

Table after Updation

(101, 'Arun', 12, 'A', 450, 90)

(102, 'David', 12, 'B', 400, 80)

(103, 'Anand', 12, 'B', 350, 70)

(104, 'Reena', 12, 'A', 380, 76)

(105, 'Neha', 12, 'B', 420, 84)

(106, 'Raj', 12, 'A', 430, 86)

You might also like