0% found this document useful (0 votes)
14 views23 pages

Xii Cs Practical File Updated

Uploaded by

aryan1sharma2008
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)
14 views23 pages

Xii Cs Practical File Updated

Uploaded by

aryan1sharma2008
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

CENTRAL BOARD OF SECONDARY

EDUCATION

A PRACTICAL RECORD FILE IS SUBMITTED TO DEPARTMENT OF COMPUTER SCIENCE FOR

THE PARTIAL FULLFILLMENT OF SSCE EXAMINATION FOR THE ACADEMIC SESSION:

2023-24

SUBMITTED BY: AMAN PATEL

HOD(COMPUTER):MS.LEENA MALOHTRA

CLASS: XII-A

ROLL NO:
ACKNOWLEDGEMENT

I wish to express my deep sense of gratitude and


indebtedness to our learned teacher Ms. Leena Malhotra
, PGT COMPUTER SCIENCE, G.D Goenka Public School,
Dwarka for her invaluable help, advice and guidance in
the preparation of this project.

I am also greatly indebted to our Principal Ms. Anita


Khosla and school authorities for providing me with the
facilities and requisite laboratory conditions for making
this practical file.

I also extend my thanks to a number of teachers, my


classmates and friends who helped me to complete this
practical file successfully.

AMAN PATEL
CERTIFICATE

This is to certify that AMAN PATEL, student of ClassXII,


G.D Goenka Public School, Dwarka has completed the
PRACTICAL FILE during the academic year 2023-24
towards partial fulfillment of credit for the Computer
Science practical evaluation of CBSE SSCE-2023 and
submitted satisfactory report, as compiled in the
following pages, under my
supervision.

Total number of practical certified are: 24

Internal Examiner External Examiner

Date: School Seal Principal


CONTENTS
S.No PRACTICAL-TITLE Date Signature
I WORKING WITH FUNCTION
1 Write a python program using a function to print factorial number series
from n to m numbers.
2 Write a python program to accept the username "Admin" as the default
argument and password 123 entered by the user to allow login into the
system.
3 Write a python program to demonstrate the concept of variable length
argument to calculate the product and power of the first 10 numbers.
II DATA FILE HANDLING
4 Create a text file "intro.txt" in python and ask the user to write a single
line of text by user input.
5 Write a program to count a total number of lines and count the total
number of lines starting with 'A', 'B', and 'C' from the file MyFile.txt.
6 Write a program to replace all spaces from text with - (dash) from the file
intro.txt.
7 Write a program to know the cursor position and print the text according
to the below-given specifications:
• Print the initial position
• Move the cursor to 4th position
• Display next 5 characters
• Move the cursor to the next 10 characters
• Print the current cursor position
• Print next 10 characters from the current cursor position

8 Write a program to store customer data into a binary file cust.dat using a
dictionary and print them on screen after reading them. The customer
data contains ID as key, and name, city as values.

9 Write a program to update a record from student.dat file by its rollno.


Display the updated record on screen.
10 Write a program to write data into binary file marks.dat and display the
records of students who scored more than 95 marks.
11 Read a CSV file top5.csv and print the contents in a proper format. The
data for top5.csv file are as following:
SNo Batsman Team Runs Highest
1 K L Rahul KXI 670 132*
2 S Dhawan DC 618 106*
3 David Warner SRH 548 85*
4 Shreyas Iyer DC 519 88*
5 Ishan Kishan MI 516 99
12 Read a CSV file top5.csv and print them with tab delimiter. Ignore first
row header to print in tabular form.
13 Read a CSV file students.csv and print them with tab delimiter. Ignore
first row header to print in tabular form.
Field 1 Data Type
StudentID Integer
StudentName String
Score Interger
III DATA STRUCTURE
14 Write a program to implement a stack for the employee details (empno,
name).
15 Write a python program to check whether a string is a palindrome or not
using stack.
IV DATABASE MANAGEMENT (MySQL Queries)
16 Queries Set 1 (Fetching records)
17 Queries Set 2 (Based on Aggregate Functions)
18 Queries Set 3 (DDL Commands)
19 Queries set 4 (Based on Two Tables)
20 Queries Set 5 (Group by , Order By)
V P YTHON- MySQL Connectivity
21 Write a MySQL connectivity program in Python to
• • Create a database school
• Create a table students with the specifications - ROLLNO integer,
STNAME character(10) in MySQL and perform the following operations:
o Insert two records in it
o Display the contents of the table

22 Perform all the operations with reference to table ‘students’ through


MySQL-Python connectivity.
23 Write a menu-driven program to store data into a MySQL database
named shop and table customer as following:
1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details
24 Modify the above program and display the customer details based on the
following menu:
1. Display customer details by city
2. Display customer details by bill amount
3. Display customer details by name
4. Display customer details by category
PROGRAM 1:-

def factorial(num):
if num == 0 or num == 1:
return 1
else:
return num * factorial(num - 1)
#Main
a=int(input(“Enter a number”))
f=factorial(a)
print(“Factorial of”,a,”is”,f)
OUTPUT:-

print(“Factorial of a is:”,f)

PROGRAM 2:-

def login(username="Admin",password="123"):
user_name = input("Enter username: ")
pass_word = input("Enter password: ")
if user_name == username and pass_word == password:
print("Login successful!")
else:
print("Login failed. Invalid username or password.")
# Main
login()
OUTPUT:-

PROGRAM 3:-
calculate():
product = 1
power = 1
for num in range(1,11):
product *= num
power **= num
print("Product=",product, "Power=",power)

# Main
calculate()

OUTPUT:-

PROGRAM 4:

with open("intro.txt", "w") as file:


user_input = input("Write a single line of text: ")
file.write(user_input)
print("Text has been written to intro.txt.")

OUTPUT:-
PROGRAM 5:-
total_lines = 0
A=0
B=0
C=0
with open(‘Myfile.txt’, 'r') as file:
for line in file:
total_lines += 1
if line.startswith('A'):
A += 1
elif line.startswith('B'):
B += 1
elif line.startswith('C'):
C+= 1
print (“Total number of lines:”,total_lines)
print (“Total number of lines starting with A:”,A)
print (“Total number of lines starting with B: ”,B)
print (“Total number of lines starting with C:”,C)

OUTPUT:-

PROGRAM 6:-
with open(‘intro.txt’, 'r') as file:
f1= file.read()
f2= f1.replace(' ', '-')
file.write(modified_text)
print("Sucessfully modified")

PROGRAM 7:-
t = "This is a sphagettiiiiiii iiiiiiiii."
ip = 0
print(f"Initial Cursor Position: {ip}")
cp = 4
print(f"Moving Cursor to Position: {cp}")
print(f"Text at Cursor Position: {t[cp]}")
nc = t[cp + 1:cp + 6]
print(f"Next 5 Characters: {nc}")
cp += 10
print(f"Moving Cursor to Position: {cp}")
print(f"Current Cursor Position: {cp}")
nc = t[cp:cp + 10]
print(f"Next 10 Characters from Current Cursor Position: {nc}")

PROGRAM 8:-
import pickle
def store_customer_data(filename, customer_data):
with open(filename, 'wb') as file:
pickle.dump(customer_data, file)
print("Customer data has been stored in", filename)
def read_and_print_customer_data(filename):
with open(filename, 'rb') as file:
customer_data = pickle.load(file)
print("Customer Data:")
for customer_id, info in customer_data.items():
print("ID: {customer_id}, Name: {info['name']}, City: {info['city']}")
OUTPUT:-

PROGRAM 9:-
import pickle
def update_record(filename, rollno, updated_data):
try:
with open(filename, 'rb') as file:
student_data = pickle.load(file)
except FileNotFoundError:
print("filename not found.")
return
except EOFError:
student_data = {}
if rollno in student_data:
student_data[rollno].update(updated_data)
with open(filename, 'wb') as file:
pickle.dump(student_data, file)
print("Record with rollno”, rollno,” has been updated.")
else:
print("Record with rollno”, rollno,” not found.")

OUTPUT: -

PROGRAM 10:-
import pickle
def write_data(filename, student_data):
with open(filename, 'wb') as file:
pickle.dump(student_data, file)
def display_high_scorers(filename):
try:
with open(filename, 'rb') as file:
student_data = pickle.load(file)
except FileNotFoundError:
print(f"File '{filename}' not found.")
return
except EOFError:
student_data = {}

# Display records of students who scored more than the threshold


print(“Students who scored more than”,95,”marks:")
for rollno, marks in student_data.items():
if marks > 95:
print("Roll No:”, rollno, “Marks:”,marks)

OUTPUT: -

PROGRAM 11:-
import csv
def readandprint(file_path='top5.csv'):
try:
with open(file_path, 'r', newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter='\t')
headers = next(csv_reader)
print(f"{headers[0]:<5} {headers[1]:<15} {headers[2]:<5} {headers[3]:<5} {headers[4]:<10}")
for row in csv_reader:
print(f"{row[0]:<5} {row[1]:<15} {row[2]:<5} {row[3]:<5} {row[4]:<10}")
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
OUTPUT: -

PROGRAM 12:-
import csv
def read_and_print_csv(file_path):
try:
with open(file_path, 'r', newline='') as csvfile:
csv_reader = csv.reader(csvfile, delimiter='\t')
next(csv_reader)
print("\t".join(["SNo", "Batsman", "Team", "Runs", "Highest"]))
for row in csv_reader:
print("\t".join(row))
except FileNotFoundError:
print(f"File '{file_path}' not found.")
except Exception as e:
print(f"An error occurred: {e}")

OUTPUT: -
PROGRAM 14:-
stk=[]
top=-1
def line():
print('~'*100)
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None
def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1
def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1
def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ans='y'
while ans=='y':
ch=int(input("Enter your choice:"))
if ch==1:
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
elif ch==4:
break
else:
print("Invalid Choice")
ans=input("wanna do more? y/n")

OUTPUT: -

PROGRAM 15:-
def is_palindrome(input_string):
input_string = input_string.lower()
stack = []
for char in input_string[:len(input_string)//2]:
stack.append(char)
for char in input_string[len(input_string)//2:]:
if char != stack.pop():
return False
return True
user_input = input("Enter a string: ")
if is_palindrome(user_input):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
OUTPUT: -

PROGRAM 16:-
SELECT * FROM <table name>;

SELECT column1, column2, column3 FROM your_table;


SELECT * FROM your_table WHERE column1 = 'specific_value';

PROGRAM 17:-
SELECT COUNT(*) FROM your_table;
SELECT AVG(column_name) FROM your_table;
SELECT SUM(column_name) FROM your_table;
SELECT MIN(column_name) FROM your_table;
SELECT MAX(column_name) FROM your_table;
SELECT COUNT(DISTINCT column_name) FROM your_table;
SELECT column_name, COUNT(*) FROM your_table GROUP BY column_name;
SELECT AVG(column_name) FROM your_table WHERE condition;
PROGRAM 18:-
1. Create a new table
CREATE TABLE your_table ( column1 datatype1,column2 datatype2,);

2.Alter an existing table (add a new column)


ALTER TABLE your_table ADD COLUMN new_column datatype;

3.Modify the data type of a column


ALTER TABLE your_table MODIFY COLUMN existing_column new_datatype;

4.Drop a column from a table


ALTER TABLE your_table DROP COLUMN column_to_drop;

5.Add a primary key to a table


ALTER TABLE your_table ADD PRIMARY KEY (column1);

6.Add a foreign key to a table


ALTER TABLE child_tableADD FOREIGN KEY (column_in_child_table)REFERENCES parent_table
(column_in_parent_table);

7.Drop a table (remove the entire table)


DROP TABLE your_table;

PROGRAM 20:-
SELECT* FROM your_table ORDER BY column ASC;
SELECT * FROM your_table ORDER BY column DESC;
PROGRAM 21:-
import mysql.connector
def create_connection():
try:
connection =
mysql.connector.connect(host="your_host",user="your_user",password="your_password" )
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None

def create_database(connection, database_name):


try:
cursor = connection.cursor()
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {database_name}")
print(f"Database '{database_name}' created successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")

def create_table(connection, database_name, table_name):


try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"CREATE TABLE IF NOT EXISTS {table_name} (ROLLNO INT, STNAME
CHAR(10))")
print(f"Table '{table_name}' created successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")
def insert_records(connection, database_name, table_name, records):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
for record in records:
cursor.execute(f"INSERT INTO {table_name} (ROLLNO, STNAME) VALUES (%s, %s)", record)
connection.commit()
print("Records inserted successfully.")
except mysql.connector.Error as err:
connection.rollback()
print(f"Error: {err}")

def display_table(connection, database_name, table_name):


try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name}")
records = cursor.fetchall()
print("\nContents of the table:")
for record in records:
print(f"ROLLNO: {record[0]}, STNAME: {record[1]}")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Main
try:
connection = create_connection()
if connection:
create_database(connection, "school")
create_table(connection, "school", "students")
records_to_insert = [(1, 'Aman'), (2, 'luffy')]
insert_records(connection, "school", "students", records_to_insert)
display_table(connection, "school", "students")
except Exception as e:
print(f"An error occurred: {e}")

PROGRAM 23:-
import mysql.connector
def create_connection():
try:
connection =
mysql.connector.connect(host="your_host",user="your_user",password="your_password" )
return connection
except mysql.connector.Error as err:
print(f"Error: {err}")
return None

def create_database(connection, database_name):


try:
cursor = connection.cursor()
cursor.execute(f"CREATE DATABASE IF NOT EXISTS {database_name}")
print(f"Database '{database_name}' created successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")

def create_table(connection, database_name, table_name):


try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"CREATE TABLE IF NOT EXISTS {table_name} (ROLLNO INT, STNAME
CHAR(10))")
print(f"Table '{table_name}' created successfully.")
except mysql.connector.Error as err:
print(f"Error: {err}")
# Function to add customer details
def add_customer(connection, database_name, table_name, name, age, address):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"INSERT INTO {table_name} (NAME, AGE, ADDRESS) VALUES (%s, %s, %s)",
(name, age, address))
connection.commit()
print("Customer details added successfully.")
except mysql.connector.Error as err:
connection.rollback()
print(f"Error: {err}")
# Function to update customer details
def update_customer(connection, database_name, table_name, customer_id, name, age, address):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"UPDATE {table_name} SET NAME=%s, AGE=%s, ADDRESS=%s WHERE ID=%s",
(name, age, address, customer_id))
connection.commit()
print("Customer details updated successfully.")
except mysql.connector.Error as err:
connection.rollback()
print(f"Error: {err}")
# Function to delete customer details
def delete_customer(connection, database_name, table_name, customer_id):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"DELETE FROM {table_name} WHERE ID=%s", (customer_id,))
connection.commit()
print("Customer details deleted successfully.")
except mysql.connector.Error as err:
connection.rollback()
print(f"Error: {err}")
# Function to display all customer details
def display_customers(connection, database_name, table_name):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name}")
records = cursor.fetchall()
print("\nAll Customer Details:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Age: {record[2]}, Address: {record[3]}")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Main
try:
connection = create_connection()
if connection:
create_database(connection, "shop")
create_table(connection, "shop", "customer")

while True:
print("\nMenu:")
print("1. Add customer details")
print("2. Update customer details")
print("3. Delete customer details")
print("4. Display all customer details")
print("5. Exit")

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

if choice == '1':
name = input("Enter customer name: ")
age = int(input("Enter customer age: "))
address = input("Enter customer address: ")
add_customer(connection, "shop", "customer", name, age, address)
elif choice == '2':
customer_id = int(input("Enter customer ID to update: "))
name = input("Enter new name: ")
age = int(input("Enter new age: "))
address = input("Enter new address: ")
update_customer(connection, "shop", "customer", customer_id, name, age, address)

elif choice == '3':


customer_id = int(input("Enter customer ID to delete: "))
delete_customer(connection, "shop", "customer", customer_id)

elif choice == '4':


display_customers(connection, "shop", "customer")

elif choice == '5':


print("Exiting program.")
break

else:
print("Invalid choice. Please enter a number between 1 and 5.")

except Exception as e:
print(f"An error occurred: {e}")

PROGRAM 24:-
# Function to display customer details by city
def display_by_city(connection, database_name, table_name, city):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name} WHERE CITY = %s", (city,))
records = cursor.fetchall()
print(f"\nCustomer Details in {city}:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Age: {record[2]}, Address: {record[3]}, City: {record[4]},
Bill Amount: {record[5]}, Category: {record[6]}")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Function to display customer details by bill amount


def display_by_bill_amount(connection, database_name, table_name, min_amount, max_amount):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name} WHERE BILL_AMOUNT BETWEEN %s AND
%s", (min_amount, max_amount))
records = cursor.fetchall()
print(f"\nCustomer Details with Bill Amount between {min_amount} and {max_amount}:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Age: {record[2]}, Address: {record[3]}, City: {record[4]},
Bill Amount: {record[5]}, Category: {record[6]}")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Function to display customer details by name


def display_by_name(connection, database_name, table_name, name):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name} WHERE NAME = %s", (name,))
records = cursor.fetchall()
print(f"\nCustomer Details for {name}:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Age: {record[2]}, Address: {record[3]}, City: {record[4]},
Bill Amount: {record[5]}, Category: {record[6]}")
except mysql.connector.Error as err:
print(f"Error: {err}")

# Function to display customer details by category


def display_by_category(connection, database_name, table_name, category):
try:
cursor = connection.cursor()
cursor.execute(f"USE {database_name}")
cursor.execute(f"SELECT * FROM {table_name} WHERE CATEGORY = %s", (category,))
records = cursor.fetchall()
print(f"\nCustomer Details in Category {category}:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Age

You might also like