[go: up one dir, main page]

0% found this document useful (0 votes)
9 views4 pages

Class12 CS Codes

The document provides 20 important Python codes and SQL queries for Class 12 Computer Science, covering various programming concepts such as recursion, exception handling, file operations, data structures, searching and sorting algorithms, and database operations. Each code snippet includes a brief description and its output. The examples serve as practical exercises for students to enhance their programming skills.

Uploaded by

mani2008gagan
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)
9 views4 pages

Class12 CS Codes

The document provides 20 important Python codes and SQL queries for Class 12 Computer Science, covering various programming concepts such as recursion, exception handling, file operations, data structures, searching and sorting algorithms, and database operations. Each code snippet includes a brief description and its output. The examples serve as practical exercises for students to enhance their programming skills.

Uploaded by

mani2008gagan
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/ 4

CBSE Class 12 Computer Science - 20 Important

Codes with Output

1. Write a Python function to find factorial of a number using recursion.


def fact(n):
if n==0 or n==1:
return 1
return n * fact(n-1)

print(fact(5))
Output:
120

2. Write a Python program to find the maximum of 3 numbers using a


function.
def maximum(a, b, c):
return max(a, b, c)

print(maximum(12, 45, 32))


Output:
45

3. Write a program to demonstrate exception handling (divide by zero).


try:
a = 10
b = 0
print(a/b)
except ZeroDivisionError:
print("Division by zero is not allowed.")
Output:
Division by zero is not allowed.

4. Write a program to read and display content of a text file.


f = open("sample.txt", "w")
f.write("Hello Class 12")
f.close()

f = open("sample.txt", "r")
print(f.read())
f.close()
Output:
Hello Class 12

5. Write a program to append text to a file.


f = open("sample.txt", "a")
f.write("\nThis is appended text.")
f.close()

f = open("sample.txt", "r")
print(f.read())
f.close()
Output:
Hello Class 12
This is appended text.

6. Write a program to push and pop elements from a stack using list.
stack = []
stack.append(10)
stack.append(20)
print("Stack after pushes:", stack)
stack.pop()
print("Stack after pop:", stack)
Output:
Stack after pushes: [10, 20]
Stack after pop: [10]

7. Write a program for linear search in a list.


def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1

print(linear_search([10,20,30,40], 30))
Output:
2

8. Write a program to perform bubble sort on a list.


arr = [34, 12, 5, 66, 1]
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print(arr)
Output:
[1, 5, 12, 34, 66]

9. Write a program to demonstrate binary search.


def binary_search(arr, x):
low, high = 0, len(arr)-1
while low <= high:
mid = (low+high)//2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid+1
else:
high = mid-1
return -1

print(binary_search([10,20,30,40,50], 40))
Output:
3

10. Write a program to demonstrate CSV file writing and reading.


import csv

with open("data.csv", "w", newline="") as f:


writer = csv.writer(f)
writer.writerow(["Name", "Marks"])
writer.writerow(["Ravi", 85])

with open("data.csv", "r") as f:


reader = csv.reader(f)
for row in reader:
print(row)
Output:
['Name', 'Marks']
['Ravi', '85']

11. Write a SQL query to create a table named Student with fields Roll, Name,
Marks.
CREATE TABLE Student(
Roll INT PRIMARY KEY,
Name VARCHAR(50),
Marks INT
);
Output:
Table created successfully.

12. Write a SQL query to insert a record into Student table.


INSERT INTO Student VALUES(1, 'Ravi', 90);
Output:
1 row inserted.

13. Write a SQL query to display all records from Student table.
SELECT * FROM Student;
Output:
1 | Ravi | 90

14. Write a SQL query to update marks of student with Roll=1 to 95.
UPDATE Student SET Marks=95 WHERE Roll=1;
Output:
1 row updated.

15. Write a SQL query to delete a student record where Roll=1.


DELETE FROM Student WHERE Roll=1;
Output:
1 row deleted.

16. Write a program in Python to connect with MySQL database (using


mysql.connector).
import mysql.connector

con = mysql.connector.connect(host="localhost", user="root", password="1234", database="school")


if con.is_connected():
print("Connected to MySQL")
con.close()
Output:
Connected to MySQL
17. Write a program to count frequency of each word in a text file.
f = open("sample.txt", "w")
f.write("hello world hello")
f.close()

f = open("sample.txt", "r")
data = f.read().split()
freq = {}
for w in data:
freq[w] = freq.get(w, 0) + 1
print(freq)
f.close()
Output:
{'hello': 2, 'world': 1}

18. Write a program to demonstrate try-except-finally block.


try:
a = int("abc")
except ValueError:
print("Invalid conversion.")
finally:
print("Finally block executed.")
Output:
Invalid conversion.
Finally block executed.

19. Write a Python program to demonstrate stack using functions.


stack = []
def push(x):
stack.append(x)
def pop():
return stack.pop() if stack else None

push(5)
push(10)
print(pop())
print(stack)
Output:
10
[5]

20. Write a Python program to sort student records (name, marks) by marks.
students = [("Ravi", 85), ("Anita", 92), ("Karan", 78)]
students.sort(key=lambda x: x[1])
print(students)
Output:
[('Karan', 78), ('Ravi', 85), ('Anita', 92)]

You might also like