0% found this document useful (0 votes)
4 views24 pages

12 TH Practical File

The document contains a series of Python and SQL programs designed for Class 12 Computer Science practicals, covering topics such as variable declaration, arithmetic operations, user input, conditional statements, loops, functions, exception handling, file handling, and database operations. Each program includes objectives, code snippets, and expected outputs to aid in understanding the concepts. The document serves as a comprehensive guide for students to practice and apply their programming skills.
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)
4 views24 pages

12 TH Practical File

The document contains a series of Python and SQL programs designed for Class 12 Computer Science practicals, covering topics such as variable declaration, arithmetic operations, user input, conditional statements, loops, functions, exception handling, file handling, and database operations. Each program includes objectives, code snippets, and expected outputs to aid in understanding the concepts. The document serves as a comprehensive guide for students to practice and apply their programming skills.
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
You are on page 1/ 24

Class 12 Computer Science Practical File Programs.

Program 1: Basic Variables and Printing


Objective: Learn how to declare variables of different data types and print their values.
# Program 1: Basic Variables and Printing

# Assigning values to variables of different types

name = "Alice" # String

age = 30 # Integer

height = 5.5 # Float

is_student = False # Boolean

# Printing variable values

print("Name:", name)

print("Age:", age)

print("Height:", height)

print("Is student:", is_student)

# Printing a combined message

print(name, "is", age, "years old and", height, "feet tall.")

Output:
Name: Alice

Age: 30

Height: 5.5

Is student: False

Alice is 30 years old and 5.5 feet tall.

Program 2: Arithmetic Operations


Objective: Understand different arithmetic operators in Python.
# Program 2: Arithmetic Operations

a = 10

b = 3

print("a + b =", a + b) # Addition

print("a - b =", a - b) # Subtraction


print("a * b =", a * b) # Multiplication

print("a / b =", a / b) # Division

print("a // b =", a // b) # Floor division

print("a % b =", a % b) # Modulus (remainder)

print("a ** b =", a ** b) # Exponentiation

Expected Output:
a + b = 13

a - b = 7

a * b = 30

a / b = 3.3333333333333335

a // b = 3

a % b = 1

a ** b = 1000

Program 3: User Input and Type Conversion


Objective: Learn how to get input from users and convert data types.
# Program 3: User Input and Type Conversion

name_input = input("Enter your name: ")

age_str = input("Enter your age: ")

age_int = int(age_str)

print("Hello, " + name_input + "!")

print("You are", age_int, "years old.")

print("Next year, you will be", age_int + 1, "years old.")

Output:
Enter your name: Bob

Enter your age: 25

Hello, Bob!

You are 25 years old.

Next year, you will be 26 years old.

Program 4: Conditional Statements (if-elif-else)


Objective: Learn how to use conditional statements for decision making.
# Program 4: if-elif-else Statement (Grading)

score_str = input("Enter your score (0-100): ")


score = int(score_str)

if score >= 90:

grade = "A"

elif score >= 80:

grade = "B"

elif score >= 70:

grade = "C"

elif score >= 60:

grade = "D"

else:

grade = "F"

print("Your grade is:", grade)

Example Interaction:
Enter your score (0-100): 85

Your grade is: B

Program 5: For Loop with range()


Objective: Learn how to use for loops with the range() function.
# Program 5: for Loop with range()

print("Numbers from 0 to 4:")

for i in range(5):

print(i)

print("\nEven numbers from 2 to 8:")

for num in range(2, 10, 2):

print(num)

Expected Output:
Numbers from 0 to 4:

4
Even numbers from 2 to 8:

Program 6: While Loop


Objective: Learn how to use while loops for repetitive tasks.
# Program 6: while Loop

count = 1

print("Counting up to 5 using a while loop:")

while count <= 5:

print(count)

count += 1

print("Loop finished.")

Expected Output:
Counting up to 5 using a while loop:

Loop finished.

Program 7: Simple User-Defined Function


Objective: Learn how to create and call basic functions.
# Program 7: Simple User-Defined Function

def greet_user():

user_name = "Guest"

print("Hello, " + user_name + "! Welcome.")

greet_user()

greet_user()
Expected Output:
Hello, Guest! Welcome.

Hello, Guest! Welcome.

Program 8: Function with Parameters and Return Value


Objective: Learn how to create functions with parameters and return values.
# Program 8: Function with Parameters and Return Value

def add_numbers(num1, num2):

total = num1 + num2

return total

result1 = add_numbers(5, 10)

result2 = add_numbers(-3, 8)

print("Sum 1:", result1)

print("Sum 2:", result2)

Expected Output:
Sum 1: 15

Sum 2: 5

Program 9: Exception Handling (try-except)


Objective: Learn how to handle errors using try-except blocks.
# Program 9: try-except for ValueError

print("Enter a number. I will try to convert it to an integer.")

try:

num_input_str = input("Enter something: ")

num_int = int(num_input_str)

print("Successfully converted! Your number is:", num_int)

except ValueError:

print("Error: Could not convert that to an integer.")

print("Program execution continues...")

Output (with invalid input):


Enter a number. I will try to convert it to an integer.
Enter something: hello

Error: Could not convert that to an integer.

Program execution continues...

Program 10: Writing to a Text File


Objective: Learn how to write data to text files.
# Program 10: Writing to a Text File

file_name = "my_notes.txt"

try:

with open(file_name, "w") as file_object:

file_object.write("This is the first line of my notes.\n")

file_object.write("Python file handling is useful.\n")

file_object.write("Adding a number: " + str(42) + "\n")

print("Successfully wrote to '", file_name, "'")

except IOError:

print("An error occurred while writing to '", file_name, "'")

Expected Output:
Successfully wrote to ' my_notes.txt '

File Content (my_notes.txt):


This is the first line of my notes.

Python file handling is useful.

Adding a number: 42

Program 11: Reading from a Text File


Objective: Learn how to read data from text files.
# Program 11: Reading from a Text File

file_name = "my_notes.txt"

try:

with open(file_name, "r") as file_object:

print("\n--- Content of '", file_name, "' ---")

lines = file_object.readlines()

for line in lines:


print(line, end='')

print("\n--- End of Content ---")

except FileNotFoundError:

print("Error: The file '", file_name, "' was not found.")

except IOError:

print("An error occurred while reading '", file_name, "'")

Expected Output:
--- Content of ' my_notes.txt ' ---

This is the first line of my notes.

Python file handling is useful.

Adding a number: 42

--- End of Content ---

Program 12: Using the Math Module


Objective: Learn how to import and use the math module.
# Program 12: Using the math Module

import math

number = 16

square_root = math.sqrt(number)

print("The square root of", number, "is", square_root)

value = 3.7

print("The ceiling of", value, "is", math.ceil(value))

print("The floor of", value, "is", math.floor(value))

print("The value of pi is approximately:", math.pi)

Expected Output:
The square root of 16 is 4.0

The ceiling of 3.7 is 4

The floor of 3.7 is 3

The value of pi is approximately: 3.141592653589793

Program 13: Writing Data to a CSV File


Objective: Learn how to write structured data to CSV files.
# Program 13: Writing Data to a CSV File
import csv

file_name = "student_data.csv"

data_to_write = [

["Name", "Age", "Grade"],

["Alice", 10, "A"],

["Bob", 11, "B+"],

["Charlie", 10, "A-"]

try:

with open(file_name, "w", newline='') as csvfile:

csv_writer = csv.writer(csvfile)

csv_writer.writerows(data_to_write)

print("Data successfully written to '", file_name, "'")

except IOError:

print("An error occurred while writing to '", file_name, "'")

Expected Output:
Data successfully written to ' student_data.csv '

File Content (student_data.csv):


Name,Age,Grade

Alice,10,A

Bob,11,B+

Charlie,10,A-

Program 14: Reading Data from a CSV File


Objective: Learn how to read structured data from CSV files.
# Program 14: Reading Data from a CSV File

import csv

file_name = "student_data.csv"

try:

with open(file_name, "r", newline='') as csvfile:

csv_reader = csv.reader(csvfile)
print("\n--- Content of '", file_name, "' ---")

for row in csv_reader:

print(row)

print("--- End of Content ---")

except FileNotFoundError:

print("Error: The file '", file_name, "' was not found.")

except IOError:

print("An error occurred while reading '", file_name, "'")

Expected Output:
--- Content of ' student_data.csv ' ---

['Name', 'Age', 'Grade']

['Alice', '10', 'A']

['Bob', '11', 'B+']

['Charlie', '10', 'A-']

--- End of Content ---

Program 15: Using Random Number Generator


Objective: Learn how to generate random numbers and make random choices.
# Program 15: Using Random Number Generator

import random

random_float = random.random()

print("Random float:", random_float)

random_integer = random.randint(1, 10)

print("Random integer (1-10):", random_integer)

my_list = ["apple", "banana", "cherry", "date"]

random_choice = random.choice(my_list)

print("Random choice from list:", random_choice)

Output (will vary each time):


Random float: 0.1234567890123456

Random integer (1-10): 3

Random choice from list: cherry


Program 16: Implementing a Stack using a Python List
Objective: Learn how to implement a stack data structure using Python lists.
# Program 16: Implementing a Stack using a Python List

stack = []

# Push operations

stack.append("Book A")

stack.append("Book B")

stack.append("Book C")

print("Stack after pushes:", stack)

# Pop operation

if stack:

item_removed = stack.pop()

print("Popped item:", item_removed)

print("Stack after pop:", stack)

else:

print("Stack is empty, cannot pop.")

# Peek operation

if stack:

top_item = stack[-1]

print("Top item (peek):", top_item)

print("Stack after peek:", stack)

else:

print("Stack is empty, cannot peek.")

Expected Output:
Stack after pushes: ['Book A', 'Book B', 'Book C']

Popped item: Book C

Stack after pop: ['Book A', 'Book B']

Top item (peek): Book B

Stack after peek: ['Book A', 'Book B']

Program 17: Implementing a Queue using a Python List


Objective: Learn how to implement a queue data structure using Python lists.
# Program 17: Implementing a Queue using a Python List

queue = []

# Enqueue operations

queue.append("Person 1")

queue.append("Person 2")

queue.append("Person 3")

print("Queue after enqueues:", queue)

# Dequeue operation

if queue:

item_removed = queue.pop(0)

print("Dequeued item:", item_removed)

print("Queue after dequeue:", queue)

else:

print("Queue is empty, cannot dequeue.")

# Peek operation

if queue:

front_item = queue[0]

print("Front item (peek):", front_item)

print("Queue after peek:", queue)

else:

print("Queue is empty, cannot peek.")

Expected Output:
Queue after enqueues: ['Person 1', 'Person 2', 'Person 3']

Dequeued item: Person 1

Queue after dequeue: ['Person 2', 'Person 3']

Front item (peek): Person 2

Queue after peek: ['Person 2', 'Person 3']

Program 18: Create Student Table and Insert Data (SQL)


Objective: Learn how to create a database table and insert initial data.
-- Program 18: Create Student Table and Insert Data

CREATE TABLE students (

student_id INT PRIMARY KEY,


name VARCHAR(50),

age INT,

grade VARCHAR(2),

marks INT

);

-- Insert sample data

INSERT INTO students VALUES (1, 'Alice', 20, 'A', 85);

INSERT INTO students VALUES (2, 'Bob', 19, 'B', 78);

INSERT INTO students VALUES (3, 'Charlie', 21, 'A', 92);

INSERT INTO students VALUES (4, 'Diana', 20, 'C', 65);

INSERT INTO students VALUES (5, 'Eve', 22, 'B', 80);

Output:
Table 'students' created successfully.

5 rows inserted successfully.

Program 19: ALTER Table Operations (SQL)


Objective: Learn how to modify table structure using ALTER commands.
-- Program 19: ALTER Table Operations

-- Add new attribute

ALTER TABLE students ADD COLUMN email VARCHAR(100);

-- Modify data type

ALTER TABLE students MODIFY COLUMN name VARCHAR(100);

-- Drop attribute

ALTER TABLE students DROP COLUMN email;

-- Display table structure

DESCRIBE students;

Output:
Column 'email' added successfully.

Column 'name' modified successfully.

Column 'email' dropped successfully.


Table Structure:

+------------+-------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+------------+-------------+------+-----+---------+-------+

| student_id | int | NO | PRI | NULL | |

| name | varchar(100)| YES | | NULL | |

| age | int | YES | | NULL | |

| grade | varchar(2) | YES | | NULL | |

| marks | int | YES | | NULL | |

+------------+-------------+------+-----+---------+-------+

Program 20: UPDATE Table Data (SQL)


Objective: Learn how to modify existing data in tables.
-- Program 20: UPDATE Table Data

-- Update single record

UPDATE students SET marks = 88 WHERE student_id = 2;

-- Update multiple records

UPDATE students SET grade = 'A' WHERE marks >= 85;

-- Update with calculation

UPDATE students SET age = age + 1 WHERE grade = 'C';

-- Display updated data

SELECT * FROM students;

Output:
1 row updated.

2 rows updated.

1 row updated.

+------------+---------+-----+-------+-------+

| student_id | name | age | grade | marks |

+------------+---------+-----+-------+-------+

| 1 | Alice | 20 | A | 85 |

| 2 | Bob | 19 | A | 88 |
| 3 | Charlie | 21 | A | 92 |

| 4 | Diana | 21 | C | 65 |

| 5 | Eve | 22 | B | 80 |

+------------+---------+-----+-------+-------+

Program 21: ORDER BY for Sorting Data (SQL)


Objective: Learn how to sort data in ascending and descending order.
-- Program 21: ORDER BY for Sorting Data

-- Sort by marks in ascending order

SELECT * FROM students ORDER BY marks ASC;

-- Sort by marks in descending order

SELECT * FROM students ORDER BY marks DESC;

-- Sort by multiple columns

SELECT * FROM students ORDER BY grade ASC, marks DESC;

Output:
Ascending order by marks:

+------------+---------+-----+-------+-------+

| student_id | name | age | grade | marks |

+------------+---------+-----+-------+-------+

| 4 | Diana | 21 | C | 65 |

| 5 | Eve | 22 | B | 80 |

| 1 | Alice | 20 | A | 85 |

| 2 | Bob | 19 | A | 88 |

| 3 | Charlie | 21 | A | 92 |

+------------+---------+-----+-------+-------+

Descending order by marks:

+------------+---------+-----+-------+-------+

| student_id | name | age | grade | marks |

+------------+---------+-----+-------+-------+

| 3 | Charlie | 21 | A | 92 |

| 2 | Bob | 19 | A | 88 |

| 1 | Alice | 20 | A | 85 |
| 5 | Eve | 22 | B | 80 |

| 4 | Diana | 21 | C | 65 |

+------------+---------+-----+-------+-------+

Program 22: DELETE Records from Table (SQL)


Objective: Learn how to remove specific records from tables.
-- Program 22: DELETE Records from Table

-- Delete specific record

DELETE FROM students WHERE student_id = 4;

-- Delete based on condition

DELETE FROM students WHERE marks < 70;

-- Display remaining data

SELECT * FROM students;

-- Count remaining records

SELECT COUNT(*) as remaining_students FROM students;

Output:
1 row deleted.

0 rows deleted (no records match condition).

+------------+---------+-----+-------+-------+

| student_id | name | age | grade | marks |

+------------+---------+-----+-------+-------+

| 1 | Alice | 20 | A | 85 |

| 2 | Bob | 19 | A | 88 |

| 3 | Charlie | 21 | A | 92 |

| 5 | Eve | 22 | B | 80 |

+------------+---------+-----+-------+-------+

+-------------------+

| remaining_students |

+-------------------+

| 4 |
+-------------------+

Program 23: GROUP BY with Aggregate Functions (SQL)


Objective: Learn how to group data and use aggregate functions.
-- Program 23: GROUP BY with Aggregate Functions

-- Group by grade and find statistics

SELECT

grade,

COUNT(*) as student_count,

MIN(marks) as min_marks,

MAX(marks) as max_marks,

SUM(marks) as total_marks,

AVG(marks) as average_marks

FROM students

GROUP BY grade;

-- Group by age range

SELECT

CASE

WHEN age < 20 THEN 'Under 20'

WHEN age BETWEEN 20 AND 21 THEN '20-21'

ELSE 'Above 21'

END as age_group,

COUNT(*) as count

FROM students

GROUP BY age_group;

Output:
Statistics by grade:

+-------+---------------+-----------+-----------+-------------+---------------+

| grade | student_count | min_marks | max_marks | total_marks | average_marks |

+-------+---------------+-----------+-----------+-------------+---------------+

| A | 3 | 85 | 92 | 265 | 88.33 |

| B | 1 | 80 | 80 | 80 | 80.00 |

+-------+---------------+-----------+-----------+-------------+---------------+
Statistics by age group:

+-----------+-------+

| age_group | count |

+-----------+-------+

| Under 20 | 1 |

| 20-21 | 2 |

| Above 21 | 1 |

+-----------+-------+

Program 24: Python-SQL Integration - Database Connection


Objective: Learn how to connect Python with SQLite database.
# Program 24: Python-SQL Integration - Database Connection

import sqlite3

# Connect to database (creates if doesn't exist)

conn = sqlite3.connect('school.db')

cursor = conn.cursor()

# Create students table

cursor.execute('''

CREATE TABLE IF NOT EXISTS students (

student_id INTEGER PRIMARY KEY,

name TEXT NOT NULL,

age INTEGER,

grade TEXT,

marks INTEGER

''')

print("Database connected successfully!")

print("Students table created successfully!")

# Close connection

conn.close()

Output:
Database connected successfully!
Students table created successfully!

Program 25: Python-SQL Integration - Insert Data


Objective: Learn how to insert data into database using Python.
# Program 25: Python-SQL Integration - Insert Data

import sqlite3

# Connect to database

conn = sqlite3.connect('school.db')

cursor = conn.cursor()

# Insert single record

cursor.execute('''

INSERT INTO students (name, age, grade, marks)

VALUES (?, ?, ?, ?)

''', ('Alice Johnson', 20, 'A', 85))

# Insert multiple records

students_data = [

('Bob Smith', 19, 'B', 78),

('Charlie Brown', 21, 'A', 92),

('Diana Prince', 20, 'C', 65),

('Eve Adams', 22, 'B', 80)

cursor.executemany('''

INSERT INTO students (name, age, grade, marks)

VALUES (?, ?, ?, ?)

''', students_data)

# Commit changes

conn.commit()

print("Single record inserted successfully!")

print(f"{len(students_data)} records inserted successfully!")

print(f"Total records in database: {cursor.rowcount}")


# Close connection

conn.close()

Output:
Single record inserted successfully!

4 records inserted successfully!

Total records in database: 4

Program 26: Python-SQL Integration - Read and Display Data


Objective: Learn how to retrieve and display data from database using Python.
# Program 26: Python-SQL Integration - Read and Display Data

import sqlite3

# Connect to database

conn = sqlite3.connect('school.db')

cursor = conn.cursor()

# Fetch all records

cursor.execute('SELECT * FROM students')

all_students = cursor.fetchall()

print("All Students:")

print("-" * 60)

print(f"{'ID':<5} {'Name':<15} {'Age':<5} {'Grade':<7} {'Marks':<7}")

print("-" * 60)

for student in all_students:

print(f"{student[0]:<5} {student[1]:<15} {student[2]:<5} {student[3]:<7}


{student[4]:<7}")

# Fetch specific records with condition

cursor.execute('SELECT name, marks FROM students WHERE grade = ?', ('A',))

a_grade_students = cursor.fetchall()

print("\nStudents with Grade A:")

print("-" * 25)
for student in a_grade_students:

print(f"{student[0]}: {student[1]} marks")

# Close connection

conn.close()

Output:
All Students:

------------------------------------------------------------

ID Name Age Grade Marks

------------------------------------------------------------

1 Alice Johnson 20 A 85

2 Bob Smith 19 B 78

3 Charlie Brown 21 A 92

4 Diana Prince 20 C 65

5 Eve Adams 22 B 80

Students with Grade A:

-------------------------

Alice Johnson: 85 marks

Charlie Brown: 92 marks

Program 27: Python-SQL Integration - Update and Delete


Operations
Objective: Learn how to update and delete data using Python.
# Program 27: Python-SQL Integration - Update and Delete Operations

import sqlite3

# Connect to database

conn = sqlite3.connect('school.db')

cursor = conn.cursor()

# Update single record

cursor.execute('''

UPDATE students

SET marks = ?
WHERE name = ?

''', (88, 'Bob Smith'))

print(f"Updated {cursor.rowcount} record(s)")

# Update multiple records

cursor.execute('''

UPDATE students

SET grade = 'A'

WHERE marks >= 85

''')

print(f"Updated {cursor.rowcount} record(s) to grade A")

# Delete record

cursor.execute('DELETE FROM students WHERE marks < 70')

print(f"Deleted {cursor.rowcount} record(s)")

# Show remaining records

cursor.execute('SELECT name, grade, marks FROM students')

remaining_students = cursor.fetchall()

print("\nRemaining Students:")

print("-" * 30)

for student in remaining_students:

print(f"{student[0]}: Grade {student[1]}, Marks {student[2]}")

# Commit changes

conn.commit()

# Close connection

conn.close()

Output:
Updated 1 record(s)

Updated 2 record(s) to grade A

Deleted 1 record(s)
Remaining Students:

------------------------------

Alice Johnson: Grade A, Marks 85

Bob Smith: Grade A, Marks 88

Charlie Brown: Grade A, Marks 92

Eve Adams: Grade B, Marks 80

Program 28: Python-SQL Integration - Advanced Queries


with Aggregations
Objective: Learn how to perform complex queries with GROUP BY and aggregate functions using
Python.
# Program 28: Python-SQL Integration - Advanced Queries with Aggregations

import sqlite3

# Connect to database

conn = sqlite3.connect('school.db')

cursor = conn.cursor()

# Group by grade with aggregate functions

cursor.execute('''

SELECT

grade,

COUNT(*) as student_count,

MIN(marks) as min_marks,

MAX(marks) as max_marks,

AVG(marks) as avg_marks,

SUM(marks) as total_marks

FROM students

GROUP BY grade

ORDER BY grade

''')

grade_stats = cursor.fetchall()

print("Statistics by Grade:")
print("-" * 80)

print(f"{'Grade':<7} {'Count':<7} {'Min':<7} {'Max':<7} {'Average':<10}


{'Total':<7}")

print("-" * 80)

for stat in grade_stats:

print(f"{stat[0]:<7} {stat[1]:<7} {stat[2]:<7} {stat[3]:<7} {stat[4]:<10.2f}


{stat[5]:<7}")

# Overall statistics

cursor.execute('''

SELECT

COUNT(*) as total_students,

AVG(age) as avg_age,

AVG(marks) as avg_marks,

MIN(marks) as lowest_marks,

MAX(marks) as highest_marks

FROM students

''')

overall_stats = cursor.fetchone()

print(f"\nOverall Statistics:")

print("-" * 40)

print(f"Total Students: {overall_stats[0]}")

print(f"Average Age: {overall_stats[1]:.1f} years")

print(f"Average Marks: {overall_stats[2]:.2f}")

print(f"Lowest Marks: {overall_stats[3]}")

print(f"Highest Marks: {overall_stats[4]}")

# Close connection

conn.close()

Output:
Statistics by Grade:

--------------------------------------------------------------------------------

Grade Count Min Max Average Total

--------------------------------------------------------------------------------
A 3 85 92 88.33 265

B 1 80 80 80.00 80

Overall Statistics:

----------------------------------------

Total Students: 4

Average Age: 20.5 years

Average Marks: 86.25

Lowest Marks: 80

Highest Marks: 92

You might also like