0% found this document useful (0 votes)
26 views32 pages

AISSCE 2025-26 Computer Science Practical

This document is a practical file for the Computer Science subject (083) for Class XII, covering various programming tasks and projects for the AISSCE 2025-26 session. It includes a certificate of completion, acknowledgments, a table of contents, and detailed implementations of programming exercises such as calculating factorials, checking for palindromes, and file operations. The file serves as a comprehensive guide for students to demonstrate their practical skills in computer science.

Uploaded by

abhigautam954820
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)
26 views32 pages

AISSCE 2025-26 Computer Science Practical

This document is a practical file for the Computer Science subject (083) for Class XII, covering various programming tasks and projects for the AISSCE 2025-26 session. It includes a certificate of completion, acknowledgments, a table of contents, and detailed implementations of programming exercises such as calculating factorials, checking for palindromes, and file operations. The file serves as a comprehensive guide for students to demonstrate their practical skills in computer science.

Uploaded by

abhigautam954820
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

AISSCE 2025-26

COMPUTER SCIENCE
PRACTICAL FILE

Name: ________________________
Class: XII - ____
Roll No: ______________________
School: ______________________
Computer Science (083) Practical File

CERTIFICATE
This is to certify that [Your Name] of Class XII has successfully completed the practical
file for the subject Computer Science (083) under my supervision. The programs and
projects mentioned in this file are original and cover the syllabus prescribed by CBSE
for the session 2025-26.

Teacher In-Charge External Examiner

1
Computer Science (083) Practical File

ACKNOWLEDGEMENT
I would like to express my sincere gratitude to my Computer Science teacher, [Teacher
Name], for their guidance and support in completing this practical file. I would also like
to thank our Principal for providing the necessary lab facilities which made this work
possible.

2
Computer Science (083) Practical File

Contents

Certificate 1

Acknowledgement 2

1 Menu Driven: Factorial & Fibonacci 5

2 Check for Palindrome String 7

3 Read Text File and Count Statistics 8

4 Copy Lines Not Containing ‘a’ 9

5 Count Specific Word Frequency 10

6 Binary File: Create and Search Student 11

7 Binary File: Update Marks of Student 12

8 Binary File: Delete a Student Record 13

9 CSV File: Write and Read User Data 14

10 Stack Implementation 15

11 Linear Search Algorithm 16

12 Binary Search Algorithm 17

13 Bubble Sort Algorithm 18

14 Random Number Generator (Dice) 19

15 SQL: Database & Table Creation 20

16 SQL: Alter, Update and Delete 21

17 SQL: Aggregate Functions 22

18 SQL: Order By & Distinct 23

19 SQL: Group By & Having 24

20 Connectivity: Fetch All Records 25

21 Connectivity: Insert New Record 26

22 Connectivity: Search Record 27

23 Connectivity: Update Record 28

3
Computer Science (083) Practical File

24 Connectivity: Delete Record 29

Viva Voce Questions 30

Bibliography 31

4
Computer Science (083) Practical File

1 Menu Driven: Factorial & Fibonacci


Aim: To write a menu-driven program to calculate the factorial of a number or generate
the Fibonacci series using user-defined functions.

Source Code
1 def factorial (n):
2 """ Calculates factorial of a number iteratively """
3 f = 1
4 for i in range (1, n + 1):
5 f *= i
6 return f
7

8 def fibonacci (n):


9 """ Prints Fibonacci series up to n terms """
10 a, b = 0, 1
11 print (" Fibonacci Series :", end=" ")
12 for _ in range (n):
13 print (a, end=" ")
14 a, b = b, a + b
15 print ()
16
17 # Main Menu
18 while True:
19 print ("\n--- MENU ---")
20 print ("1. Factorial ")
21 print ("2. Fibonacci Series ")
22 print ("3. Exit")
23 try:
24 ch = int( input (" Enter choice (1 -3): "))
25 if ch == 1:
26 num = int( input ("Enter a number : "))
27 print (f" Factorial of {num} is { factorial (num)}")
28 elif ch == 2:
29 n = int( input (" Enter number of terms : "))
30 fibonacci (n)
31 elif ch == 3:
32 print (" Exiting ...")
33 break
34 else:
35 print (" Invalid Choice ")
36 except ValueError :
37 print (" Please enter a valid integer .")

Output

1 --- MENU ---


2 1. Factorial
3 2. Fibonacci Series
4 3. Exit
5 Enter choice (1 -3): 1
6 Enter a number : 5

5
Computer Science (083) Practical File

7 Factorial of 5 is 120

6
Computer Science (083) Practical File

2 Check for Palindrome String


Aim: To check if a given string is a palindrome (reads the same forward and backward).

Source Code
1 def is_palindrome (s):
2 # Remove spaces and convert to lowercase for uniform comparison
3 clean_s = s. replace (" ", "").lower ()
4
5 # Check if string matches its reverse
6 if clean_s == clean_s [:: -1]:
7 return True
8 else:
9 return False
10
11 # Driver Code
12 word = input (" Enter a string : ")
13 if is_palindrome (word):
14 print (f" '{word}' is a Palindrome .")
15 else:
16 print (f" '{word}' is NOT a Palindrome .")

Output

1 Enter a string : Racecar


2 'Racecar ' is a Palindrome .

7
Computer Science (083) Practical File

3 Read Text File and Count Statistics


Aim: To read a text file named [Link] and display the count of vowels, consonants,
uppercase, and lowercase characters.

Source Code
1 def file_stats ():
2 # Creating a dummy file for demonstration
3 with open(" article .txt", "w") as f:
4 [Link](" Hello World ! Python is Amazing .")
5
6 try:
7 with open(" article .txt", "r") as f:
8 data = [Link] ()
9 vowels = 0
10 consonants = 0
11 upper = 0
12 lower = 0
13
14 for char in data:
15 if char. isalpha ():
16 if [Link] () in 'aeiou ':
17 vowels += 1
18 else:
19 consonants += 1
20
21 if char. isupper ():
22 upper += 1
23 elif char. islower ():
24 lower += 1
25
26 print ("File Content :", data)
27 print ("-" * 20)
28 print (f" Vowels : { vowels }")
29 print (f" Consonants : { consonants }")
30 print (f" Uppercase : {upper }")
31 print (f" Lowercase : {lower }")
32
33 except FileNotFoundError :
34 print ("File not found .")
35
36 file_stats ()

Output

1 File Content : Hello World! Python is Amazing .


2 --------------------
3 Vowels : 8
4 Consonants : 17
5 Uppercase : 4
6 Lowercase : 21

8
Computer Science (083) Practical File

4 Copy Lines Not Containing ‘a’


Aim: To read lines from [Link] and write those lines NOT containing the character
‘a’ into [Link].

Source Code
1 def copy_no_a ():
2 # Create source file
3 with open(" source .txt", "w") as f:
4 [Link](" Apple is red\ nBanana is yellow \ nKiwi is green \nPlum is purple ")
5
6 print (" --- Reading Source File ---")
7 with open(" source .txt", "r") as f1 , open(" target .txt", "w") as f2:
8 lines = f1. readlines ()
9 for line in lines:
10 # Check if 'a' is NOT present (case - insensitive )
11 if 'a' not in [Link] ():
12 [Link](line)
13 print (f" Copied : {line. strip ()}")
14
15 print ("\nFile copied successfully .")
16
17 copy_no_a ()

Output

1 --- Reading Source File ---


2 Copied : Kiwi is green
3 Copied : Plum is purple
4
5 File copied successfully .

9
Computer Science (083) Practical File

5 Count Specific Word Frequency


Aim: To count the occurrences of the word “the” or “The” in a text file [Link].

Source Code
1 def count_word ():
2 # Create dummy file
3 with open("story .txt", "w") as f:
4 [Link]("The sun is bright . The sky is blue. I like the sun.")
5
6 with open("story .txt", "r") as f:
7 # Read file and split into words list
8 data = [Link] ().split ()
9 count = 0
10 for word in data:
11 # Check for 'the ' ignoring case
12 if [Link] () == "the":
13 count += 1
14 print (f" Frequency of 'the ': {count }")
15
16 count_word ()

Output

1 Frequency of 'the ': 3

10
Computer Science (083) Practical File

6 Binary File: Create and Search Student


Aim: To create a binary file [Link] storing [RollNo, Name] and search for a student
by Roll No.

Source Code
1 import pickle
2
3 def create ():
4 """ Create binary file and add records """
5 f = open(" student .dat", "wb")
6 while True:
7 r = int( input ("Enter Roll No: "))
8 n = input (" Enter Name: ")
9 pickle .dump ([r, n], f)
10 if input ("Add more? (y/n): ").lower () == 'n': break
11 [Link] ()
12

13 def search ():


14 """ Search for a record in binary file"""
15 f = open(" student .dat", "rb")
16 target = int( input (" Enter Roll to Search : "))
17 found = False
18 try:
19 while True:
20 s = pickle .load(f)
21 if s[0] == target :
22 print (" Record Found :", s)
23 found = True
24 break
25 except EOFError :
26 pass
27
28 if not found: print (" Record Not Found ")
29 [Link] ()
30

31 print (" --- Step 1: Input Data ---")


32 create ()
33 print ("\n--- Step 2: Search Data ---")
34 search ()

Output

1 --- Step 1: Input Data ---


2 Enter Roll No: 101
3 Enter Name: Amit
4 Add more? (y/n): n
5
6 --- Step 2: Search Data ---
7 Enter Roll to Search : 101
8 Record Found : [101 , 'Amit ']

11
Computer Science (083) Practical File

7 Binary File: Update Marks of Student


Aim: To update the marks of a specific student in a binary file [Link].

Source Code
1 import pickle
2
3 def update_marks ():
4 # Setup initial data
5 with open("marks .dat", "wb") as f:
6 pickle .dump ({"Rno": 1, "Marks ": 80}, f)
7 pickle .dump ({"Rno": 2, "Marks ": 90}, f)
8
9 r = int(input (" Enter Roll No to update : "))
10 found = False
11 records = []
12
13 # Read all records
14 f = open(" marks .dat", "rb")
15 try:
16 while True:
17 records . append ( pickle .load(f))
18 except EOFError : pass
19 [Link] ()
20
21 # Update logic
22 f = open(" marks .dat", "wb")
23 for rec in records :
24 if rec["Rno"] == r:
25 print (" Current Marks :", rec[" Marks "])
26 rec[" Marks "] = int( input (" Enter New Marks : "))
27 found = True
28 pickle .dump(rec , f)
29 [Link] ()
30
31 if found : print (" Marks updated successfully .")
32 else: print ("Roll number not found .")
33
34 update_marks ()

Output

1 Enter Roll No to update : 2


2 Current Marks: 90
3 Enter New Marks: 95
4 Marks updated successfully .

12
Computer Science (083) Practical File

8 Binary File: Delete a Student Record


Aim: To delete a record from [Link] based on Roll No.

Source Code
1 import pickle
2
3 def delete_rec ():
4 # Initial Data Creation
5 with open(" student .dat", "wb") as f:
6 pickle .dump ([1, "Avi"], f)
7 pickle .dump ([2, "Ben"], f)
8
9 r = int(input (" Enter Roll No to delete : "))
10 records = []
11

12 # Read all records


13 f = open(" student .dat", "rb")
14 try:
15 while True:
16 records . append ( pickle .load(f))
17 except EOFError : pass
18 [Link] ()
19
20 # Rewrite file excluding the deleted record
21 f = open(" student .dat", "wb")
22 deleted = False
23 for rec in records :
24 if rec [0] != r:
25 pickle .dump(rec , f)
26 else:
27 deleted = True
28 [Link] ()
29

30 if deleted : print (" Record Deleted .")


31 else: print (" Record not found .")
32
33 delete_rec ()

Output

1 Enter Roll No to delete : 1


2 Record Deleted .

13
Computer Science (083) Practical File

9 CSV File: Write and Read User Data


Aim: To write UserID and Password to a CSV file and read the content.

Source Code
1 import csv
2
3 def csv_operations ():
4 # Writing to CSV
5 with open("users .csv", "w", newline ="") as f:
6 writer = csv. writer (f)
7 writer . writerow ([" UserID ", " Password "]) # Header
8 writer . writerow (["admin ", " admin123 "])
9 writer . writerow (["guest ", " guest123 "])
10
11 print (" --- Reading CSV File ---")
12 # Reading from CSV
13 with open("users .csv", "r") as f:
14 reader = csv. reader (f)
15 for row in reader :
16 print (row)
17

18 csv_operations ()

Output

1 --- Reading CSV File ---


2 ['UserID ', 'Password ']
3 ['admin ', 'admin123 ']
4 ['guest ', 'guest123 ']

14
Computer Science (083) Practical File

10 Stack Implementation
Aim: To implement a Stack data structure using a Python List with Push, Pop, and Dis-
play operations.

Source Code
1 stack = []
2
3 def push(s):
4 val = int( input (" Enter value to push: "))
5 s. append (val)
6 print (f"Value {val} pushed to stack .")
7
8 def pop(s):
9 if not s:
10 print ("Stack Underflow ! ( Empty Stack )")
11 else:
12 print (" Popped Element :", [Link] ())
13
14 def display (s):
15 if not s:
16 print ("Stack is Empty .")
17 else:
18 print ("Stack Elements (Top to Bottom ):")
19 print (s[:: -1])
20
21 while True:
22 print ("\n--- STACK OPERATIONS ---")
23 print ("1. Push 2. Pop 3. Display 4. Exit")
24 ch = int( input (" Enter choice : "))
25 if ch == 1: push(stack)
26 elif ch == 2: pop(stack)
27 elif ch == 3: display (stack)
28 elif ch == 4: break
29 else: print (" Invalid choice !")

Output

1 --- STACK OPERATIONS ---


2 1. Push 2. Pop 3. Display 4. Exit
3 Enter choice : 1
4 Enter value to push: 50
5 Value 50 pushed to stack.

15
Computer Science (083) Practical File

11 Linear Search Algorithm


Aim: To search for an element in a list using the Linear Search algorithm.

Source Code
1 def linear_search (lst , target ):
2 for i in range (len(lst)):
3 if lst[i] == target :
4 return i # Return index
5 return -1 # Not found
6

7 numbers = [10, 50, 30, 70, 80, 20]


8 print ("List:", numbers )
9 key = int( input (" Enter number to search : "))
10
11 idx = linear_search (numbers , key)
12
13 if idx != -1:
14 print (f" Element found at index {idx}")
15 else:
16 print (" Element not found .")

Output

1 List: [10, 50, 30, 70, 80, 20]


2 Enter number to search : 30
3 Element found at index 2

16
Computer Science (083) Practical File

12 Binary Search Algorithm


Aim: To search for an element in a sorted list using the Binary Search algorithm.

Source Code
1 def binary_search (arr , x):
2 low = 0
3 high = len(arr) - 1
4
5 while low <= high:
6 mid = (low + high) // 2
7
8 if arr[mid] == x:
9 return mid
10 elif arr[mid] < x:
11 low = mid + 1 # Ignore left half
12 else:
13 high = mid - 1 # Ignore right half
14
15 return -1
16
17 data = [10, 20, 30, 40, 50, 60, 70] # List must be sorted
18 print (" Sorted List:", data)
19 key = int( input (" Enter key to search : "))
20
21 res = binary_search (data , key)
22
23 if res != -1: print (f" Found at index {res}")
24 else: print ("Not Found ")

Output

1 Sorted List: [10, 20, 30, 40, 50, 60, 70]


2 Enter key to search : 40
3 Found at index 3

17
Computer Science (083) Practical File

13 Bubble Sort Algorithm


Aim: To sort a list of integers in ascending order using Bubble Sort.

Source Code
1 def bubble_sort (arr):
2 n = len(arr)
3 # Traverse through all array elements
4 for i in range (n):
5 # Last i elements are already in place
6 for j in range (0, n-i -1):
7 # Swap if the element found is greater than the next element
8 if arr[j] > arr[j+1]:
9 arr[j], arr[j+1] = arr[j+1], arr[j]
10
11 numbers = [64, 34, 25, 12, 22, 11, 90]
12 print (" Original List:", numbers )
13
14 bubble_sort ( numbers )
15
16 print (" Sorted List: ", numbers )

Output

1 Original List: [64, 34, 25, 12, 22, 11, 90]


2 Sorted List: [11, 12, 22, 25, 34, 64, 90]

18
Computer Science (083) Practical File

14 Random Number Generator (Dice)


Aim: To simulate a dice roll using the random module.

Source Code
1 import random
2
3 print (" --- Dice Simulator ---")
4 while True:
5 input (" Press Enter to roll the dice ...")
6 # randint includes both end points
7 score = random . randint (1, 6)
8 print (f"You rolled a: [ {score } ]")
9
10 if input ("Roll again ? (y/n): ").lower () == 'n':
11 print ("Game Over!")
12 break

Output

1 --- Dice Simulator ---


2 Press Enter to roll the dice ...
3 You rolled a: [ 4 ]
4 Roll again? (y/n): n
5 Game Over!

19
Computer Science (083) Practical File

15 SQL: Database & Table Creation


Aim: To create a database named SCHOOL and a table STUDENT.

SQL Query
1 -- 1. Create Database
2 CREATE DATABASE SCHOOL ;
3
4 -- 2. Use Database
5 USE SCHOOL ;
6
7 -- 3. Create Table
8 CREATE TABLE STUDENT (
9 AdmNo INT PRIMARY KEY ,
10 Name VARCHAR (20) ,
11 Class INT ,
12 Marks FLOAT
13 );
14
15 -- 4. Insert Records
16 INSERT INTO STUDENT VALUES (101 , 'Ankit ', 12, 85.5);
17 INSERT INTO STUDENT VALUES (102 , 'Bhavna ', 12, 92.0);
18 INSERT INTO STUDENT VALUES (103 , 'Chirag ', 11, 78.0);
19 INSERT INTO STUDENT VALUES (104 , 'Diya ', 12, 95.0);
20
21 -- 5. Show Records
22 SELECT * FROM STUDENT ;

20
Computer Science (083) Practical File

16 SQL: Alter, Update and Delete


Aim: To modify table structure (Alter), modify data (Update), and remove records (Delete).

SQL Query
1 -- 1. Add new column Stream
2 ALTER TABLE STUDENT ADD Stream VARCHAR (10);
3
4 -- 2. Update Stream for all students
5 UPDATE STUDENT SET Stream = 'Science ';
6

7 -- 3. Delete a specific student record


8 DELETE FROM STUDENT WHERE AdmNo = 101;
9
10 -- 4. Display result
11 SELECT * FROM STUDENT ;

21
Computer Science (083) Practical File

17 SQL: Aggregate Functions


Aim: To use Aggregate functions (SUM, MAX, MIN, AVG, COUNT) on the table.

SQL Query
1 -- Highest Marks
2 SELECT MAX(Marks) AS Highest_Score FROM STUDENT ;
3
4 -- Lowest Marks
5 SELECT MIN(Marks) AS Lowest_Score FROM STUDENT ;
6

7 -- Average Marks
8 SELECT AVG(Marks) AS Average_Score FROM STUDENT ;
9
10 -- Total Number of Students
11 SELECT COUNT (*) AS Total_Students FROM STUDENT ;

22
Computer Science (083) Practical File

18 SQL: Order By & Distinct


Aim: To sort data using ORDER BY and find unique values using DISTINCT.

SQL Query
1 -- Sort students by Marks (High to Low)
2 SELECT * FROM STUDENT ORDER BY Marks DESC;
3
4 -- Find distinct Classes in the table
5 SELECT DISTINCT Class FROM STUDENT ;

23
Computer Science (083) Practical File

19 SQL: Group By & Having


Aim: To group records and apply conditions on groups.

SQL Query
1 -- Count number of students in each class
2 SELECT Class , COUNT (*) FROM STUDENT GROUP BY Class;
3
4 -- Show Classes having more than 5 students ( Example Logic )
5 SELECT Class , COUNT (*) FROM STUDENT
6 GROUP BY Class
7 HAVING COUNT (*) > 5;

24
Computer Science (083) Practical File

20 Connectivity: Fetch All Records


Aim: To connect Python with MySQL database and fetch all records from STUDENT table.

Source Code
1 import mysql . connector
2
3 try:
4 # Establish Connection
5 con = mysql. connector . connect (
6 host=" localhost ",
7 user="root",
8 password =" password ",
9 database =" SCHOOL "
10 )
11

12 if con. is_connected ():


13 cur = con. cursor ()
14 cur. execute (" SELECT * FROM STUDENT ")
15
16 # Fetch all rows
17 records = cur. fetchall ()
18
19 print ("Data from Database :")
20 for row in records :
21 print (row)
22
23 except mysql . connector .Error as err:
24 print (" Error :", err)
25
26 finally :
27 if 'con ' in locals () and con. is_connected ():
28 [Link] ()

25
Computer Science (083) Practical File

21 Connectivity: Insert New Record


Aim: To insert a new student record into the MySQL database using Python.

Source Code
1 import mysql . connector
2
3 try:
4 con = mysql. connector . connect (
5 host=" localhost ", user="root", password =" password ", database =" SCHOOL "
6 )
7 cur = con. cursor ()
8
9 # Parameterized Query
10 sql = " INSERT INTO STUDENT (AdmNo , Name , Class , Marks ) VALUES (%s, %s, %s, %
s)"
11 val = (105 , "Esha", 12, 88.0)
12
13 cur. execute (sql , val)
14 con. commit () # Save changes
15

16 print (f"{cur. rowcount } record inserted .")


17
18 except mysql . connector .Error as e:
19 print (e)
20 finally :
21 [Link] ()

26
Computer Science (083) Practical File

22 Connectivity: Search Record


Aim: To search for a specific student record using Python-MySQL connectivity.

Source Code
1 import mysql . connector
2
3 try:
4 con = mysql. connector . connect (
5 host=" localhost ", user="root", password =" password ", database =" SCHOOL "
6 )
7 cur = con. cursor ()
8
9 adm = int( input (" Enter AdmNo to Search : "))
10 query = " SELECT * FROM STUDENT WHERE AdmNo = %s"
11

12 cur. execute (query , (adm ,))


13 rec = cur. fetchone () # Fetch single record
14
15 if rec:
16 print (" Record Found :", rec)
17 else:
18 print (" Record Not Found .")
19
20 except mysql . connector .Error as e:
21 print (e)
22 finally :
23 [Link] ()

27
Computer Science (083) Practical File

23 Connectivity: Update Record


Aim: To update the marks of a student using Python-MySQL connectivity.

Source Code
1 import mysql . connector
2
3 try:
4 con = mysql. connector . connect (
5 host=" localhost ", user="root", password =" password ", database =" SCHOOL "
6 )
7 cur = con. cursor ()
8
9 adm = int( input (" Enter AdmNo to Update : "))
10 marks = float ( input (" Enter New Marks : "))
11

12 sql = " UPDATE STUDENT SET Marks =%s WHERE AdmNo =%s"
13 val = (marks , adm)
14
15 cur. execute (sql , val)
16 con. commit ()
17

18 print (" Record Updated Successfully .")


19
20 except mysql . connector .Error as e:
21 print (e)
22 finally :
23 [Link] ()

28
Computer Science (083) Practical File

24 Connectivity: Delete Record


Aim: To delete a student record using Python-MySQL connectivity.

Source Code
1 import mysql . connector
2
3 try:
4 con = mysql. connector . connect (
5 host=" localhost ", user="root", password =" password ", database =" SCHOOL "
6 )
7 cur = con. cursor ()
8
9 adm = int( input (" Enter AdmNo to Delete : "))
10

11 sql = " DELETE FROM STUDENT WHERE AdmNo = %s"


12 cur. execute (sql , (adm ,))
13 con. commit ()
14
15 if cur. rowcount > 0:
16 print (" Record Deleted .")
17 else:
18 print (" Record Not Found .")
19
20 except mysql . connector .Error as e:
21 print (e)
22 finally :
23 [Link] ()

29
Computer Science (083) Practical File

VIVA VOCE QUESTIONS


Q1: What is the difference between read(), readline() and readlines()?
Ans: read() reads the entire file as a string. readline() reads a single line. readlines()
reads all lines and returns them as a list.
Q2: What is pickle in Python?
Ans: Pickle is a module used for serializing (saving) and deserializing (loading) Python
objects (like lists, dictionaries) to/from a binary file.
Q3: What is the difference between ‘w’ and ‘a’ modes in file handling?
Ans: ‘w’ (Write) mode overwrites the file if it exists or creates a new one. ‘a’ (Append)
mode adds data to the end of the file without deleting existing content.
Q4: What is a Primary Key?
Ans: A Primary Key is a column (or set of columns) that uniquely identifies each row in
a table. It cannot contain NULL values.
Q5: What is the difference between count(*) and count(column_name)?
Ans: count(*) counts all rows including NULLs. count(column_name) counts only non-
NULL values in that specific column.
Q6: Why do we use [Link]() in connectivity?
Ans: commit() is used to save the changes (Insert, Update, Delete) made to the database
permanently. Without it, changes are not saved.

30
Computer Science (083) Practical File

BIBLIOGRAPHY
1. Textbook: Computer Science with Python by Sumita Arora / Preeti Arora (Class XII).

2. Reference: CBSE Curriculum 2025-26 ([Link]).

3. Software: Python 3.x, MySQL Server (8.0), MySQL Connector.

4. Web Resources: [Link], [Link].

31

Common questions

Powered by AI

Connecting Python with a MySQL database facilitates dynamic data manipulation and retrieval by allowing Python programs to interact with database tables directly. Using Python scripts, one can dynamically execute SQL queries to insert new records, update existing ones, or delete them based on program logic. Retrieval operations, like using cursors to fetch database records into Python data structures, enable high-level data manipulation and analysis within the Python environment. This integration enables robust application development where database operations become part of the solution's functionality .

To find unique class values in the STUDENT table, the SQL statement would be 'SELECT DISTINCT Class FROM STUDENT;'. The DISTINCT clause is important as it filters out duplicate values from the result set, ensuring only unique entries are returned. This is particularly useful when you need to know which unique categories or values exist within a column, avoiding redundancy in the output .

SQL Aggregate Functions such as SUM, MAX, and AVG enhance data analysis by providing essential summarized information from large datasets. SUM allows for the calculation of total values across specified columns, MAX finds the maximum value, and AVG computes the average value. These functions enable efficient data analysis to obtain insights such as the highest marks, total marks, or average marks in the STUDENT table without the need for manual calculations, thus aiding decision-making processes .

In a bubble sort algorithm, elements are swapped when a current element is greater than the next one, moving the larger element towards the end of the list with each pass. This repeated comparison and swapping process continues, pushing the largest unsorted element to its correct position at each iteration. Although simple, bubble sort is generally inefficient for large datasets due to its O(n^2) time complexity, as it requires repeated passes through the entire list .

Exception handling in Python enhances file and database operations by managing errors gracefully, which improves both robustness and fault tolerance. When operations encounter unexpected issues, such as file not found errors or database connectivity issues, exception handling allows for predefined responses rather than abrupt program termination. This approach enables the logging of error messages, cleaning up resources, or retrying operations, ensuring that the system continues to operate smoothly and reduces the risk of data corruption or loss .

The pickle module in Python is used for serializing (saving) and deserializing (loading) Python objects, making it suitable for managing student records in a binary file. You can serialize Python objects such as lists or dictionaries representing student records, saving them to a binary file. When needed, these records can be deserialized back into Python objects for retrieval and manipulation. This process helps in maintaining a structured and versatile storage solution that preserves data types across program executions .

'w' (Write) mode overwrites the file if it exists or creates a new one. This means any existing content in the file will be deleted before new data is written. 'a' (Append) mode, on the other hand, adds new data to the end of the file without deleting existing content, allowing you to keep and expand upon the current data .

Using parameterized queries in Python is crucial for preventing SQL injection attacks. By separating SQL logic from data, parameterized queries ensure that user input is treated strictly as data, rather than part of the SQL statement, preventing malicious input from being executed as SQL code. This approach significantly enhances security by sanitizing data inputs, maintaining data integrity, and safeguarding against unauthorized access or damage to the database .

The read() function reads the entire file content as a single string, making it suitable for situations where you need to process or analyze the whole content at once. readline() reads a single line, ideal for parsing files line-by-line for efficient memory usage when dealing with large files. readlines() reads all the lines into a list, useful when you want to manipulate lines as separate items but do not need to conserve memory as strictly as with readline().

A Stack implemented using a Python list allows data to be managed in a Last In, First Out (LIFO) manner. The operations you can perform include 'push' to add an element to the top of the stack, 'pop' to remove the top element, and 'display' to view all the elements from top to bottom. These operations help manage how data can be accessed and modified .

You might also like