0% found this document useful (0 votes)
28 views31 pages

Computer Science Project

Very useful for class 12

Uploaded by

warlordmihawk7
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)
28 views31 pages

Computer Science Project

Very useful for class 12

Uploaded by

warlordmihawk7
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/ 31

Program 1

# Recursively find th factorial of a natural number.

def factorial(n):

if (n==1 or n==0):

return (n * factorial(n - 1))

# EXAMPLE :-

num = 5;

print("number : ",num)

print("Factorial : ",factorial(num))
OUTPUT :

number : 5
Factorial : 120
PROGRAM 2

def recursive_sum(lst):

# Base case: an empty list has a sum of 0

if not lst:

return 0

# Recursive case: sum of the first element and the sum of the rest of the list

else:

return lst[0] + recursive_sum(lst[1:])

# Example usage:

my_list = [1, 2, 3, 4, 5]

result = recursive_sum(my_list)

print(f"The sum of elements in the list is: {result}")

120
OUTPUT :

The sum of elements in the list is: 15


PROGRAM 3 :

def fibonacci(n):

# Base case: Fibonacci of 0 is 0, and Fibonacci of 1 is 1

if n == 0:

return 0

elif n == 1:

return 1

# Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)

else:

return fibonacci(n-1) + fibonacci(n-2)

# Example usage: nth_fibonacci = 10 # Change this to the

desired value of n result = fibonacci(nth_fibonacci)

print(f"The {nth_fibonacci}th Fibonacci number is: {result}")


OUTPUT :

The 10th Fibonacci number is: 55


PROGRAM 4

def display_words_with_a_sharp(file_path):

try:

with open(file_path, 'r') as file

# Read the file line by line

for line in file:

# Tokenize the line into words

words = line.split()

# Display words ending with 'a#'

for word in words:

if word.endswith('a#'):

print(word)

except FileNotFoundError:

print(f"Error: File '{file_path}' not found.")


PROGRAM 5
# Vowels & Consonants count

str = input("Type the string: ")


vowel_count=0
consonants_count=0
vowel = set("aeiouAEIOU")
for alphabet in str:
if alphabet in vowel:
vowel_count=vowel_count +1
elif alphabet == chr(32):
consonants_count=consonants_count
else:
consonants_count=consonants_count+1

print("Number of Vowels in ",str," is :",vowel_count)


print("Number of Consonants in ",str," is :",consonants_count)

# Upper and lower case count

uppercase_count=0
lowercase_count=0
for elem in str:
if elem.isupper():
uppercase_count += 1
elif elem.islower():
lowercase_count += 1

print("Number of UPPER Case in ",str,"' is :",uppercase_count)

print("Number of lower case in ",str,"' is :",lowercase_count)


Type the string: "Welcome to cbsepython. Best website to learn cbse computer
science"

OUTPUT :

('Number of Vowels in ', 'Welcome to cbsepython. Best website to learn cbse


computer science', ' is :', 20)
('Number of Consonants in ', 'Welcome to cbsepython. Best website to learn cbse
computer science', ' is :', 37)
('Number of UPPER Case in ', 'Welcome to cbsepython. Best website to learn cbse
computer science', "' is :", 2)
('Number of lower case in ', 'Welcome to cbsepython. Best website to learn cbse
computer science', "' is :", 54)
>>>
PROGRAM 6
import pickle:

def write_data_to_binary_file(file_name,data):

with open(file_name, 'wb') as file:

pickle.dump(data, file)

def get_name_by_roll_number(file_name,target_roll_number):

with open(file_name, 'rb') as file:

student_data = pickle.load(file)

for record in student_data:

if record['roll_number'] == target_roll_number:

return record['name']

return None

# Example data

student_data = [

{"name": "Alice", "roll_number": 101},

{"name": "Bob", "roll_number": 102},

{"name": "Charlie", "roll_number": 103},

{"name": "David", "roll_number": 104},

file_name = "student_data_pickle.bin"

write_data_to_binary_file(file_name, student_data) target_roll_number =

int(input("Enter roll number to get the name: ")) found_name =

get_name_by_roll_number(file_name, target_roll_number)

# Display the result

if found_name is not

None:

print(f"Name for Roll Number {target_roll_number}: {found_name}")

else:

print(f"Roll Number {target_roll_number} not found.")


EXAMPLE RUN

Enter roll number to get the name: 101

Name for Roll Number 101: Alice

Enter roll number to get the name: 103

Name for Roll Number 103: Charlie


PROGRAM 7
Import pickle

def write_records(file, records):

pickle.dump(records, file)

def read_records(file):

try:

records = pickle.load(file)

return records

except EOFError:

return {}

def.update_records(records):

while True:

try:

roll_number = int(input("Enter roll number (0 to exit): "))

if roll_number == 0:

break # Exit loop if roll_number is 0

marks = float(input("Enter marks: "))

records[roll_number] = marks

except ValueError:

print("Invalid input. Please enter a valid roll number and marks.")

def main():

file_name = 'student_records.pkl'

try:

try:

with open(file_name, 'rb') as file:

records = read_records(file)

except FileNotFoundError:

records = {}

update_records(records)

with open(file_name, 'wb') as file:

write_records(file, records)

print(f"Updated records written to {file_name}.")

except Exception as e:

print(f"Error: {e}")

if __name__ == "__main__":

main()
EXAMPLE RUN
Enter roll number (0 to exit): 05

Enter marks: 99

Enter roll number (0 to exit): 07

Enter marks: 97

Enter roll number (0 to exit): 0

Updated records written to student_records.pkl.


PROGRAM 8

myfile = open("Answer.txt", "r")


newfile = open("nswer.txt", "w")
line = ""
while line:
line = myfile.readline()
if 'a' not in line:
newfile.write(line)

myfile.close()

newfile.close()

print("Newly created file contains")


print("------------")

newfile = open("nswer.txt","r")

line = ""

while line:

line = newfile.readline()

print(line)

newfile.close()
PROGRAM 9

import random

def roll_dice():

return random.randint(1, 6)

def main():

print("Welcome to the Dice Simulator!")

while True:
input("Press Enter to roll the dice...")

result = roll_dice()
print(f"You rolled: {result}")

play_again = input("Do you want to roll again? (yes/no): ").lower()

if play_again != 'yes':
break

print("Thanks for playing!")

if __name__ == "__main__":
main()
EXAMPLE RUN

Welcome to the Dice Simulator!

Press Enter to roll the dice...

You rolled: 6

Do you want to roll again? (yes/no): yes

Press Enter to roll the dice...

You rolled: 3

Do you want to roll again? (yes/no): no

Thanks for playing!


PROGRAM 10
class Stack:

def __init__(self):

self.q = Queue()

def is_empty(self):

return self.q.is_empty()

def push(self, data):

self.q.enqueue(data)

def pop(self):

for _ in range(self.q.get_size() - 1):

dequeued = self.q.dequeue()

self.q.enqueue(dequeued)

return self.q.dequeue()

class Queue:

def __init__(self):

self.items = []

self.size = 0

def is_empty(self):

return self.items == []

def enqueue(self, data):

self.size += 1

self.items.append(data)

def dequeue(self):

self.size -= 1

return

self.items.pop(0)
def get_size(self):

return self.size

s = Stack()

print('Menu')

print('push <value>')

print('pop') print('quit')

while True:

do = input('What would you like to do? ').split()

operation = do[0].strip().lower()

if operation == 'push':

s.push(int(do[1]))

elif operation == 'pop':

if s.is_empty():

print('Stack is empty.')

else:

print('Popped value: ', s.pop())

elif operation == 'quit':

break
EXAMPLE RUN
Menu

push <value> pop

quit

What would you like to do? push 4

What would you like to do? push 4

What would you like to do? push 5

What would you like to do? push 8

What would you like to do? pop

Popped value: 8

What would you like to do? pop

Popped value: 5

What would you like to do? pop

Popped value: 4

What would you like to do? pop

Popped value: 4

What would you like to do? pop

Stack is empty. What would you

like to do? quit


PROGRAM 11
import csv
def write_to_csv(file_name, data):
with open(file_name, 'w', newline='') ascsvfile:
fieldnames = ['User_ID', 'Password']
writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
writer.writeheader()
for row in data:
writer.writerow(row)
def read_from_csv(file_name):
data = []
with open(file_name, 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
def search_password(data, user_id):
for row in data:
if row['User_ID'] == user_id:
return row['Password']
return None
def main():
file_name = 'user_data.csv'
user_data = []
while True:
user_id = input("Enter User ID (type 'exit' to stop): ")
if user_id.lower() == 'exit':
break

password = input("Enter Password: ")


user_data.append({'User_ID': user_id, 'Password': password})
write_to_csv(file_name, user_data)
print(f"Data written to {file_name}.")
read_data = read_from_csv(file_name)
search_user_id = input("Enter User ID to search for password: ")
found_password = search_password(read_data, search_user_id)
if found_password:
print(f"Password for User ID {search_user_id}: {found_password}")

else:

print(f"User ID {search_user_id} not found.")


if __name__ == "__main__":
EXAMPLE RUN

Enter User ID (type 'exit' to stop): vanshduhoon07

Enter Password: vanshjaat1

Enter User ID (type 'exit' to stop): vanshjaat7

Enter Password: vanshjaat2

Enter User ID (type 'exit' to stop): exit

Data written to user_data.csv.

Enter User ID to search for password: vanshduhoon07

Password for User ID vanshduhoon07: vanshjaat1


PROGRAM 12
CREATE TABLE IF NOT EXISTS student (

student_id INT PRIMARY KEY,

first_name VARCHAR(50) NOT NULL,

last_name VARCHAR(50) NOT NULL,

age INT,

marks INT

);

INSERT INTO student (student_id, first_name, last_name, age, marks)

VALUES

(1, 'John', 'Doe', 18, 85),

(2, 'Jane', 'Smith', 19, 92),

(3, 'Alice', 'Johnson', 20, 78),

(4, 'Bob', 'Williams', 18, 95);

SELECT * FROM student;

ALTER TABLE student

ADD COLUMN email VARCHAR(100);

ALTER TABLE student

MODIFY COLUMN age VARCHAR(3);

ALTER TABLE student

DROP COLUMN marks;

UPDATE student

SET age = 21

WHERE student_id = 3;

SELECT * FROM student

ORDER BY age ASC;

SELECT * FROM student

ORDER BY marks DESC;

DELETE FROM student

WHERE student_id = 2;

SELECT

MIN(age) AS min_age,

MAX(age) AS max_age,

SUM(age) AS total_age,

COUNT(*) AS total_students,

AVG(age) AS avg_age

FROM student;
OUTPUT

student_id first_name last_name age marks


1 John Doe 18 85
2 Jane Smith 19 92
3 Alice Johnson 20 78 4 Bob Williams 18
95
student_id first_name last_name age email
1 John Doe 18 NULL
4 Bob Williams 18 NULL
2 Jane Smith 19 NULL
3 Alice Johnson 21 NULL

[Execution complete with exit code 1]


PROGRAM 13

import mysql.connector conn =

mysql.connector.connect(

host='your_host',

user='your_user',

password='your_password',

database='your_database'

cursor = conn.cursor() cursor.execute('''

CREATE TABLE IF NOT EXISTS student (

student_id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255) NOT NULL, age INT NOT

NULL, grade FLOAT NOT NULL

''')

cursor.executemany('''

INSERT INTO student (name, age, grade) VALUES (%s, %s, %s)

''', [

('Alice', 20, 85.5),

('Bob', 21, 90.0),

('Charlie', 19, 78.2),

('David', 22, 95.7)

])

conn.commit()
print("Initial Data:") cursor.execute('SELECT

* FROM student') for row in

cursor.fetchall():

print(row)

cursor.execute('ALTER TABLE student ADD COLUMN major VARCHAR(255)')

cursor.execute('ALTER TABLE student MODIFY COLUMN age VARCHAR(255)')

cursor.execute('UPDATE student SET grade = grade + 5 WHERE name = "Alice"')

cursor.execute('SELECT * FROM student ORDER BY grade ASC') print("\nData in

Ascending Order:") for row in cursor.fetchall():

print(row) cursor.execute('SELECT * FROM student ORDER BY

grade DESC') print("\nData in Descending Order:") for row in

cursor.fetchall():

print(row) cursor.execute('DELETE FROM student WHERE name

= "Charlie"') cursor.execute(''' SELECT age,

MIN(grade) AS min_grade,

MAX(grade) AS max_grade,

SUM(grade) AS total_grade,

COUNT(*) AS total_students,

AVG(grade) AS avg_grade

FROM student

GROUP BY age

''')

print("\nStatistics by Age:") for

row in cursor.fetchall():

print(row)

conn.close()
PROGRAM 14

import mysql.connnector as sqltor mysql = sqltor.connect(host = “localhost” , user = “learner” ,

passwd = “fast” , database = “test”) if mycon.is_connected() == False:

Print(‘Error connecting to MySQL database ‘ )

cursor = mycon.cursor()

cursor.execute(“select * from student “) data

= cursor.fetchmany(3) count =

cursor.rowcount for row in data : Print(row)

mycon.close()
OUTPUT

(101 , ‘Ruhani’ , Decimal(‘76.80’) , ‘A’ , ‘A’ , ‘Pending’ )

(102 , ‘George’ , Decimal(‘71.20’) , ‘B’ , ‘A’ , ‘Submitted’)

(103 , ‘ Simran‘ ,Decimal(‘81.20’) , ‘A’ , ‘B’ , ‘Evaluated’)


PROGRAM 15

CREATE TABLE Employee

( ID Number(4) NOT NULL PRIMARY KEY ,

First_Name Varchar(30) NOT NULL,

Last_Name Varchar (30) NOT NULL,

User_ID Varchar (10) UNIQUE ,

Salary Number (9,2) CHECK (Salary > 5000) );

MySQL responds as : Query OK , 0 rows affected


PROGRAM 16
PROGRAM 17
OUTPUT

You might also like