Professional Documents
Culture Documents
STD XII CS Rec 2023-24
STD XII CS Rec 2023-24
STD XII CS Rec 2023-24
Exp No:1
Write a Python program for random number generation that generates random numbers
between 1 to 6 (simulates a dice).
Aim: To write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).
Algorithm:
Step 1: Start
Step 2: Import random module
Step 3: Define a function diceroll()
Step 4: Under while loop write a random number generate that will generate
number from 1 to 6 using randint() method.
Step 5: Print the random generated number
Step 6: Stop
Source Code:
import random
def diceroll():
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)
diceroll()
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: 2
Write a Python program using function to compute the nth Fibonacci number.
Aim: To write a python program using function to compute the nth Fibonacci number.
Algorithm:
Step 1: Start
Step 2: Create user defined function name Fibonacci(n) write following steps
Initialize counter variable a=0 and b=1
If n < 0 return invalid input
If n =0 return 0
If n=1 return 1 else
run for loop range(n-2)
compute next number in series: c=a+b
swap a=b
b=c
Return b value
Step 3: Read x value from user.
Step 4: Call the function fibonacci(x)
Step 5: Print the nth Fibonacci series.
Step 6: Stop
Source Code:
def fibonacci(n):
a=0
b=1
if n<0:
print ("incorrect input:")
elif n==0:
print(a)
elif n==1:
print(a,b)
else:
print(a,b,end=" ")
for i in range(n-2):
c=a+b
print(c,end=" ")
a=b
b=c
print("*Printing Fibonacci Series*")
x=int(input("How many numbers you want to display : "))
print("The Fibonacci Series is: ")
fibonacci(x)
Output:
Result:
Thus the Python program using function to compute the nth Fibonacci number 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
Aim:
To write Python program to read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in the file.
Algorithm:
Step 1: Start
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using read() method
Step 4:Write the logic for counting the Vowels,Consonants,Upper case
letters,Lower case letters using islower(),isupper(),ch in [‘a’,’e’,’i’,’o’,’u’],
ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
Step 5: Close the file using close() method
Step 6: Print the Counting data.
Step 7: Stop
Source Code:
def display():
file=open("D:\\Test\\Format.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 'aeiou':
vowels+=1
elif ch in 'bcdfghjklmnpqrstvwxyz':
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)
display()
Output:
Sample Text File
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.
Exp No:4
Result: Thus, the above Python program is executed successfully and the output is
verified.
EX.NO: 5
Create a menu driven program to find factorial and sum of list of numbers using function.
Aim: To write a menu driven Python Program to find Factorial and sum of list of numbers
using function.
Source Code:
Output:
Result: Thus, the above Python program 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.
Aim: To write a Python program to remove all the lines that contain the character ‘a’ in a
file and write it to another file.
Source Code:
with open("d:\\Test\\format.txt") as f:
lines=f.readlines()
with open("d:\\Test\\second.txt",'w') as f1:
for line in lines:
if 'a' in line or "A" in line:
f1.write(line)
f2 = open("d:\\Test\\second.txt",'r')
for line in f2:
print(line,end="")
f2.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 to create a binary file with name and roll number and
perform search based on roll number.
Aim:
To write Python Program to create a binary file with name and roll number and
perform search based on roll number.
Source Code:
import pickle
def adddata():
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of Students to add data:"))
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.”
def searchdata():
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()
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:8
Write a Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers.
Aim: To write Python Program to create a binary file with roll number, name and
marks and update the marks using their roll numbers.
Source Code:
#Create a binary file with roll number, name and marks.
import pickle
with open("d:\\Test\\StudData","wb") as file:
student_data={}
no_of_students=int(input("Enter no of Students to insert in file : "))
for i in range(no_of_students):
student_data["RollNo"]=int(input("Enter roll no :"))
student_data["Name"]=input("Enter Student Name :")
student_data["Marks"]=float(input("Enter Students Marks :"))
pickle.dump(student_data,file)
student_data={}
print("Data inserted Successfully")
#Input a roll number and update the marks.
with open("d:\\Test\\StudData","rb+") as file:
student_data={}
found=False
roll_no=int(input("Enter the roll no to update marks :"))
try:
while True:
pos=file.tell()
student_data=pickle.load(file)
if(student_data["RollNo"]==roll_no):
student_data["Marks"]=float(input("Enter marks to update: "))
file.seek(pos)
pickle.dump(student_data,file)
found=True
except EOFError:
if(found==False):
print("Roll no not found")
else:
print("Students marks updated Successfully")
# print the updated data
with open("d:\\Test\\StudData","rb") as file:
student_data={}
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()
Output:
Result:
Thus the Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers is executed successfully and the output is
verified.
EX NO:9
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.
Aim: To 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.
Source Code:
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)
def read():
f=open("student.csv","r")
f.close()
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 Search 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:10
Write a Python program to create a CSV file by entering user-id and password,
read and search the password for given user-id.
Aim: To write a Python program to create a CSV file by entering user-id and
password, read and search the password for given user-id.
Source Code:
import csv
def addCsvFile():
f=open('d:\\Test\\Credentials.csv','w',newline="")
newFileWriter = csv.writer(f)
newFileWriter.writerow(['Name','UserName','PassWord'])
while True:
n=input("Enter the name of the User: ")
u=input("Create an id for the User: ")
f.close()
def readCsvFile():
with open('d:\\Test\\Credentials.csv','r') as newFile:
newFileReader = csv.reader(newFile)
for row in newFileReader:
print (row[0],row[1],row[2])
def searchCsvFile():
while True:
f=open("d:\\Test\\Credentials.csv","r")
s=input("Enter id to be searched:")
found=0
sreader=csv.reader(f)
for i in sreader:
if i[1]==s:
print(i[2])
found=1
break
if found==0:
print("sorry...no record found")
ch=input("Do you want to Search More Records: (Y/N)?")
if ch in "nN":
break
f.close()
addCsvFile()
readCsvFile()
searchCsvFile()
Output:
Result:
Thus the Python program to create a CSV file by entering user-id and password, read and
search the password for given user-id is executed successfully and the output is verified.
EX no: 11
Write a python program to search an element in a list and display its location using
binary search by using user defined function. [List and search element should be
entered by user]
Aim: To write a Python program to search an element in a list and display its
location using binary search by using user defined function.
Source Code:
def LF(l,a):
count=0
low=0
high=len(l)-1
while low<=high:
mid=int((low+high)/2)
if a==l[mid]:
Result:
Thus the Python program to search an element in a list and display its location using
binary search by using user defined function is executed successfully and the output is
verified.
EX NO:12
Write a python program to pass list to a function and double the odd values and
half even values of a list and display list element after changing.
Aim: To write a Python program to pass list to a function and double the odd
values and half even values of a list and display list element after changing.
Source Code:
def FL(a):
l1=[]
for i in range(0,len(a)):
if a[i]%2==0:
e=a[i]/2
l1.append(e)
else:
e=a[i]*2
l1.append(e)
print(l1)
Result:
Thus the Python program to pass list to a function and double the odd values and half
even values of a list and display list element after changing is executed successfully and
the output is verified.
EX NO:13
Write a Python program to implement a Stack using a list data-structure.
Aim: To write a Python program to implement a Stack using a list data-structure.
Source Code:
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:14
Write a Program to integrate SQL with Python by importing the MySQL module
and create a record of employee and display the record.
Aim: To write a program to integrate SQL with Python by importing the MySQL
module and create a record of employee and display the record.
Source Code:
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="",database="empl
oyee")
cur=con.cursor()
cur.execute("Create table EMPLOYEE(Eno int,Ename varchar(10),Esal float)")
print("table created successfully:")
while True:
Eno=int(input("Enter Employee Number :"))
break
cur.execute("select * from employee")
data=cur.fetchall()
for i in data:
print(i)
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:15
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.
Aim: To 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.
Source Code:
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:16
Write a Program to integrate SQL with Python by importing the MYSQL module
to update the employee record of entered empno.
Aim: To write a Program to integrate SQL with Python by importing the MYSQL
module to update the employee record of entered empno.
SOURCE CODE:
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:17
Write a Program to integrate SQL with Python by importing the MYSQL module
to delete the record of entered employee number.
Aim: To write a Program to integrate SQL with Python by importing the MYSQL
module to delete the record of entered employee number.
SOURCE CODE:
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.
EX NO:18
Write SQL commands for the queries based on the tables Company and Customer.
Company
Customer
(iii)
(iv)
(v)
EX NO:19
Write SQL commands for the queries based on the tables Company and Customer.
Company
Customer
(ii)
(iii)
(iv)
(v)
EX NO:20
Consider the following tables Personal and Job. Write SQL commands for the Statements
(i) to (iii) and give outputs for SQL queries (iv) to (v).
Personal
Job
(i) To display Name, Native place of all employees whose name starts with alphabet 'A'.
Ans: select name,nativeplace from personal where name like 'A%';
(ii) To display the Name, Employee number, hobby of an employee whose employee
number is 5832.
Outputs:
(i)
(ii)
(iii)
(iv)
(v)
*********************************************************