Class 12 Practical List

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

Class-12

COMPUTER SCIENCE
PROGRAM FILE
LIST OF PROGRAMS

1. Write a Program to find factorial of the entered number using function.


Solution:

num = int(input("Enter a number: "))


factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

OUTPUT:

Enter a number: 10
The factorial of 10 is 3628800
2. Write a Program to enter the number of terms and to print the Fibonacci Series.
n = 10
num1 = 0
num2 = 1
next_number = num2
count = 1

while count <= n:


print(next_number, end=" ")
count += 1
num1, num2 = num2, next_number
next_number = num1 + num2
print()

Output
1 2 3 5 8 13 21 34 55 89
3. Write a program to accept a string and print the number of uppercase, lowercase,
vowels, consonants and spaces in the given string.
Str=input(“Enter A string”)
lower=0
upper=0
for i in Str:
if(i.islower()):
lower+=1
else:
upper+=1
print("The number of lowercase characters is:",lower)
print("The number of uppercase characters is:",upper)

Output

Enter a String: Aryans International


The number of lowercase characters is:
18 The number of uppercase characters
is: 2
4. Write a Program to enter the numbers and a List to perform Linear Search using function.

def search(List, n):


for i in range(len(List)):
if List[i] == n:
return True
return False
List = [1, 2, 'sachin', 4, 'Geeks', 6]
n = input(“Enter a word to be searched ”)
if search(List, n):
print("Given word Found")
else:
print("Not Found")

OUTPUT:
Enter a word to be searched Geeks
Given word Found
5. Write a Program to enter the numbers and a List to perform Binary Search using function.

# Binary Search in python


def binarySearch(array, x, low, high):
# Repeat until the pointers low and high meet each other
while low <= high:

mid = low + (high - low)//2

if x == array[mid]:
return mid

elif x > array[mid]:


low = mid + 1

else:
high = mid - 1

return -1

array = eval(input(”Enter a list in sorted order:”))


x = int(input(“Enter a Number to be searched:“)
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")

OUTPUT:
Enter a list:[2,3,4,5,6,8,10]
Enter a Number to be searched:4
Element is present at index 2
6. Write a Program to enter the elements in a List and sort these elements using bubble sort
technique.
def bubbleSort( theSeq ):
n = len( theSeq )

for i in range( n - 1 ) :
flag = 0

for j in range(n - 1) :

if theSeq[j] > theSeq[j + 1]


: tmp = theSeq[j]
theSeq[j] = theSeq[j + 1]
theSeq[j + 1] = tmp
flag = 1

if flag == 0:
break

return theSeq

el = [21,6,9,33,3]

result = bubbleSort(el)

print (result)
7. Program to read and display file content line by line with each word separated by “ #”.
def process_file(file_path):
try:
with open(file_path, 'r') as file:
for line in file:
words = line.split()
formatted_line = '#'.join(words)
print(formatted_line)
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

# Replace 'your_file.txt' with the actual path of your text file


file_path = 'yuvi.txt'
process_file(file_path)
8. Program to read the content of file and display the total number of consonants, uppercase, vowels
and lowercase characters.
def count_characters(file_path):
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
uppercase_count = 0
lowercase_count = 0
vowel_count = 0
consonant_count = 0

try:
with open(file_path, 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1

print(f"Uppercase characters: {uppercase_count}")


print(f"Lowercase characters: {lowercase_count}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")

except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

file_path = 'file.txt'
count_characters(file_path)
9. Program to read the content of file line by line and write it to another file except for the lines
contains “a” letter in it.

f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()

f2 = open("copyMydoc.txt","r")
print(f2.read())
10. Program to store students’ details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.
import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n)....")

with open('Student_Details.csv','r',newline='') as fileobject:


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
11. Program to create binary file to store Roll no and Name, Search any Roll no and display name if
Roll no found otherwise “Roll no not found”.

pickle.dump(d2,b)
d3={'name':'third','roll number':3}
pickle.dump(d3,b)
roll=int(input('enter the desired roll no:'))

with open('students','rb')as b:
p=[]
while True:
try:
for i in range(1,4):
k=pickle.load(b)
p+=[k['roll number']]
if roll==k['roll number']:
print('the name of the desired student is:',k['name'])
if roll not in p:
print('the student of the desired roll no. does not exist')
except EOFError:
break
12. Program to create binary file to store Roll no, Name and Marks and update marks of entered Roll
no.
import pickle
def write_to_binary_file(filename, students):
with open(filename, 'wb') as file:
pickle.dump(students, file)
def read_from_binary_file(filename):
try:
with open(filename, 'rb') as file:
students = pickle.load(file)
return students
except FileNotFoundError:
return ()

# Function to update marks of a student based on roll number


def update_marks(filename, roll_no, new_marks):
students = read_from_binary_file(filename)
for student in students:
if student['roll_no'] == roll_no:
student['marks'] = new_marks
print(f"Marks updated for Roll No: {roll_no}")
write_to_binary_file(filename, students)
return
print(f"Student with Roll No {roll_no} not found.")
# Function to add a new student record
def add_student(filename, roll_no, name, marks):
students = read_from_binary_file(filename)
# Add new student to the list
new_student = {'roll_no': roll_no, 'name': name, 'marks': marks}
students.append(new_student)
# Write updated student list back to the binary file
write_to_binary_file(filename, student)

13. Program to generate random number 1-6, simulating a dice.


import random
import random

def roll_dice():
print (random.randint(1, 6))

print("""Welcome to my python random dice program!


To start press enter! Whenever you are over, type quit.""")

flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
14. Create a CSV file by entering user-id and password, read and search the password for given user-
id.
import csv
with open("7.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password:
") record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("7.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")

for i in fileobj2:
next(fileobj2)

# print(i,given)
if i[0] == given:
print(i[1])
break
15. Program to implement Stack in Python using List.

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])

def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')

choice=int (input('enter choice:'))


if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
SQL Queries
16. To write SQL-Queries for the following Questions based on the given table.
i. Create a table Student with following constraints:
Table Name: Students
Coloumn Name Data Type Size Constraints
Roll_No Integer 3 Primary Key
Name Varchar 20 Not Null
Class Varchar 3
DOB Date
Gender Char 1
City Varchar 30
Marks Double (3,2)
ii. To display the record of students in descending order of their Marks
iii. To display the class, DOB and city whose Marks is between 450 to 551.
iv. To display total number of students class wise.
v. To display the detail of students whose name start with ‘M’.
Solution:
i. CREATE TABLE Students(Roll_No int(3) primary key, Name varchar(20) NOT NULL, Class
varchar(3), DOB Date, Gender Char(1), City varchar(30), Marks Double(3,2));

ii. SELECT * FROM Students order by Marks desc;

iii. SELECT Class, DOB, city FROM Students WHERE Marks between 540 to 551;

iv. SELECT, Class, count(*) from Students group by class;

v. SELECT * from Students WHERE Name like ‘M%’;

17. To write SQL-Queries for the following Questions based on the given table.

i. Write SQL command to create above table.


ii. Write SQL command to insert one record in above table.
iii. To display CNO, CNAME, TRAVELDATE from the table TRAVEL in descending order of CNO.
iv. To display the CNAME of all customers from the table TRAVEL who are travelling by vehicle
with code Vo1 or Vo2
v. To display the CNO and CNAME of those customers from the table TRAVEL who
travelled between ‘2015-1231’ and ‘2015-05-01’.
vi. To display all the details from table TRAVEL for the customers, who have travel distance
more than 120 KM in ascending order of NOP.

Solution:
i. (a) Create table VEHICAL (VOCDE char(4) primary key, VECHICALTYPE varchar(20),
PERKM int(3));
(b) Create table TRAVEL(CNO int(3) primary key, CNAME varchar(20), TRAVELDATE DATE,
KM int(3), VCODE char(3), NOP int(3));
ii. (a) INSERT INTO VEHICAL VALUES(‘V01’, ‘VOLVO BUS’, 150);
(b) INSERT INTO TRAVEL values(101, ‘K.NAIWAL’, ’13-12-2015’,200,’V01’, 32);
iii. DISPLAY CNO,CNAME,TRAVELDATE from TRAVEL order by desc CNO;
iv.

18. Program to connect with database and store record of employee and display records.
def connect_db():
conn = mysql.connector.connect( host="localhost", # MySQL server address (localhost if local)
user="root",
return conn

def insert_employee(name, age, department, salary):


conn = connect_db()
cursor = conn.cursor() # Insert employee record into the employee table
cursor.execute(''' INSERT INTO employee (name, age, department, salary) VALUES (%s, %s, %s, %s); ''',
(name, age, department, salary))
conn.commit() # Commit the transaction
conn.close()

def display_employees():
conn = connect_db()
cursor = conn.cursor() # Retrieve all records from the employee
table cursor.execute('SELECT * FROM employee')
employees = cursor.fetchall() # Check if there are any records and display
them if employees:
print(f"{'ID':<5}{'Name':<20}{'Age':<5}{'Department':<20}{'Salary':<10}")
print("-" * 60)
for emp in employees: print(f"{emp[0]:<5}{emp[1]:<20}{emp[2]:<5}{emp[3]:<20}
{emp[4]:<10}") else: print("No
employee records found.")

conn.close()

insert_employee("Alice Johnson", 30, "HR", 50000.00)

insert_employee("Bob Smith", 25, "Engineering", 70000.00)

insert_employee("Charlie Brown", 35, "Marketing", 60000.00)

display_employees()
19. Program to connect with database and search employee number in table employee and
display record, if empno not found display appropriate message.
import mysql.connector
def connect_db():
conn = mysql.connector.connect( host="localhost", user="root", password="your_password",
database="employee_db")
return conn

def search_employee(empno):
conn = connect_db()
cursor = conn.cursor() # Query to search for the employee by empno
cursor.execute(''' SELECT * FROM employee WHERE empno = %s; ''', (empno,))
employee = cursor.fetchone()
if employee: # Employee found, displaying the details
print(f"{'Emp No':<10}{'Name':<20}{'Age':<5}{'Department':<20}{'Salary':<10}")
print("-" * 60)
print(f"{employee[0]:<10}{employee[1]:<20}{employee[2]:<5}{employee[3]:<20}
{employee[ 4]:<10}")

else:

print(f"Employee with empno {empno} not found.")

conn.close()

empno = int(input("Enter employee number (empno) to search: "))

search_employee(empno)

20. Write a program to connect Python with MySQL using database connectivity and perform the
following operations on data in database: Fetch, Update and delete the data.
A. CREATE A TABLE
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key, sname varchar(30), gender
char(1), DOB date, stream varchar(15), marks float(4,2))")
B. INSERT THE DATA:
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)", (1245, 'Arush', 'M', '2003-
10-04', 'science', 67.34))
demodb.commit( )
C. FETCH THE DATA
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("select * from student")
for i in democursor:
print(i)
D. UPDATE THE RECORD
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE DATA
import mysql.connector demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit( )

You might also like