computer assignment (2)
computer assignment (2)
With thanks,
1
Certificate
This is to certify that of class 12th of
School has completed this project under my guidance. She has
taken interest and has shown utmost sincerity while collecting,
analysing, and interpreting all relevant information required to
prepare this project. She has successfully completed the project
work in Computer Science to my satisfaction.
Signature of Principal
2
~I N D E X~
1. WAP to take input for the temperature in Fahrenheit and display the
result in degree centigrade.
Page no- 06
2. WAP to take input for the temperature in centigrade and display the result
in Fahrenheit.
Page no-06
6. Program to take student details and calculate total, percentage, and grade
based on conditions.
Page no- 09-10
7. WAP to count and display total words and length of each word in a text
file.
Page no- 11
3
9. Program to search for a roll number in a binary file, display the
corresponding student's name, and update their marks if required.
Page no-14-16
11. TABLE:PRODUCT.
Page no- 19-22
13. Write a program to calculate the sum of all the marks given in file
marks.csv. records in the file.
Page no-28
15. Program to write and read details of multiple items to a CSV file
"product.csv".
Page no-30-32
4
18. Write a Python program to connect to a MySQL database and retrieve
employee details based on the employee name.
Page no-36
5
1. WAP to take input for the temperature in Fahrenheit and display the
result in degree centigrade.
def fahrenheit_to_celsius():
fahrenheit = float(input("Enter temp in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5 / 9
print("Temp in Celsius:", celsius)
fahrenheit_to_celsius()
O/p
2. WAP to take input for the temperature in centigrade and display the
result in Fahrenheit.
def celsius_to_fahrenheit():
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
print("Temperature in Fahrenheit:", fahrenheit)
celsius_to_fahrenheit()
O/p
6
3. Write a program to enter name and percentage in a dictionary of n
number of students and display the information.
def multiple_of_7_or_11():
num = int(input("Enter a number: "))
if num % 7 == 0 or num % 11 == 0:
print("The number is a multiple of 7 or 11.")
else:
print("The number is not a multiple of 7 or 11.")
multiple_of_7_or_11()
O/p
def factorial():
num = int(input("Enter a number: "))
result = 1
for i in range(1, num + 1):
result *= i
print("Factorial:", result)
factorial()
O/p
7
5. Count various characters in the string (alphabets, uppercase,
lowercase, digits, spaces, special characters).
def count():
string = input("Enter a string: ")
alphabets = sum(1 for char in string if char.isalpha())
uppercase = sum(1 for char in string if char.isupper())
lowercase = sum(1 for char in string if char.islower())
digits = sum(1 for char in string if char.isdigit())
spaces = sum(1 for char in string if char.isspace())
special = len(string) - (alphabets + digits + spaces)
count()
O/p
8
6. Program to take student details and calculate total, percentage, and
grade based on conditions.
total = m1 + m2 + m3
percent = total / 3
print("Student:",name,"Roll No:",roll)
print("Total Marks:", total)
print("Percentage:", percent)
print("Grade:", grade)
9
O/p
10
7. Program to count and display total words and length of each word
in a text file.
# Writing to 'story.txt'
with open("story.txt", "w") as file:
s= "A quick fox jumped over the lazy dog."
file.write(s)
print("Content written to 'story.txt'.")
# Reading ‘story.txt’
with open("story.txt", "r") as file:
words = file.read().split()
print("Total number of words:", len(words))
for word in words:
print( word + ':' + str(len(word)) + " characters")
O/p
11
8. Program to display counts of vowels, consonants, uppercase, and
lowercase in a text file.
def count_characters(file_path):
vowels = "aeiouAEIOU"
uppercase = 0
lowercase = 0
vowel_count = 0
consonant_count = 0
try:
with open(file_path, 'r') as f:
text = f.read()
if char in vowels:
vowel_count += 1
elif char.isalpha() and char not in vowels:
consonant_count += 1
12
O/p
13
9. Program to search for a roll number in a binary file, display the
corresponding student's name, and update their marks if required.
import pickle
def write():
students = [
(1, 'Guki', 98),
(2, 'Ram', 90),
(3, 'Ding', 50)
]
with open('student.dat', 'wb') as file:
for student in students:
pickle.dump(student, file)
print('Data written successfully.')
def search_and_update():
roll = int(input('Enter roll number to search: '))
flag = 0
students = []
14
if flag == 0:
print("Roll number not found.")
return
def read():
print("\nCurrent student records:")
with open('student.dat', 'rb') as file:
while True:
try:
student = pickle.load(file)
print("Roll Number:", student[0], ", Name:",
student[1], ", Marks:", student[2])
except EOFError:
break
write()
search_and_update()
read()
15
O/p
16
10. Program to implement a stack using a list.
# empty stack
stack = []
# Function to push an element
def push(element):
stack.append(element)
print(element + " pushed onto stack.")
# Function to pop an element
def pop():
if stack:
removed_element = stack.pop()
print(removed_element + " popped from stack.")
else:
print("Stack is empty. Cannot pop.")
# Function to display
def display():
print("Stack:", stack)
def stack():
while True:
print("\nOptions:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
element = input("Enter an element to push: ")
push(element)
elif choice == '2':
pop()
elif choice == '3':
17
display()
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
stack()
O/p
18
11. TABLE:PRODUCT.
TABLE:CLIENT
Queries:
19
create database Shop;
USE Shop;
20
/* #1 Display details of clients whose city is "Delhi"*/
SELECT * FROM CLIENT WHERE City = 'Delhi';
O/p
QUERY 1
QUERY 2
QUERY 3
QUERY 4
21
Write the Output of the following:
–- #5 Select distinct city from client;
O/p
–- #8 Select productname,price*4
from product;
O/p
22
12. Tables: Interiors
TABLE:NEWONES
Queries
23
create table interiors (
no int primary key,
itemname varchar(50),
type varchar(20),
dateofstock date,
price int,
discount int
);
24
-- Inserting data into 'newones' table
insert into newones values
(11, 'white wood', 'double bed', '2003-03-23', 20000, 20),
(12, 'james 007', 'sofa', '2003-02-20', 15000, 15),
(13, 'tom look', 'baby cot', '2003-02-21', 7000, 10);
Queries
–- #1 To show all the information about the sofas from
the interiors table.
select * from interiors where type= 'sofa';
25
-- #8 To insert a new row in the newones table with the
following data. 14,”true Indian”,”office
table”,{28/03/03},15000,20
insert into newones values (14, 'true indian', 'office
table', '2003-03-28', 15000, 20);
O/p
Query 1
Query 2
Query 3
Query 4
Query 5
Query 6
26
Write the Output of the following:
–- #6 Select count(distinct type) from interiors;
–- #2 Select max(discount),min(discount),avg(discount)
from interiors;
27
13. Write a program to calculate the sum of all the marks given in file
marks.csv. records in the file are as follows
import csv
def write_file():
records = [
["rollno", "name", "marks"],
[1, "Suman", 71],
[2, "Aman", 67],
[3, "Teena", 88],
[4, "Mini", 90]
]
with open('marks.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(records)
print("File written successfully.")
def calculate_sum():
total_marks = 0
with open('marks.csv', 'r') as file:
reader = csv.reader(file)
next(reader)
for record in reader:
total_marks += int(record[2])
print("Sum of all marks:", total_marks)
write_file()
calculate_sum()
O/p
28
14. Write a program to add/insert records in the file data.csv.
import csv
def add_record():
while True:
admno = input("Enter Admno: ")
name = input("Enter Name: ")
class_name = input("Enter Class: ")
section = input("Enter Section: ")
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([admno, name, class_name,
section])
print("Record added successfully.")
continue_choice = input("Do you want to add
another record? (yes/no): ").lower()
if continue_choice != 'yes':
break
add_record()
O/p
29
15. Writing and reading details of multiple items to/from a CSV file
(product.csv).
import csv
def write_csv():
with open('product.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['ID', 'Name', 'Price', 'Qty'])
while True:
pid = input("Enter Prod ID: ")
name = input("Enter Prod Name: ")
price = float(input("Enter Prod Price: "))
qty = int(input("Enter Prod Quantity: "))
w.writerow([pid, name, price, qty])
cont = input("Add another prod? (yes/no):
").lower()
if cont != 'yes' or cont != ‘y’:
break
def read_csv():
try:
with open('product.csv', 'r') as f:
r = csv.reader(f)
print("\nProduct Details:")
for row in r:
print(row)
except FileNotFoundError:
print("File 'product.csv' does not exist. Write
data first.")
def main():
30
while True:
print("\nMenu:")
print("1. Write to CSV")
print("2. Read from CSV")
print("3. Exit"
ch = input("Enter choice (1/2/3): ")
if ch == '1':
write_csv()
elif ch == '2':
read_csv()
elif ch == '3':
print("Exitinggg")
break
else:
print("Invalid choice.")
main()
31
O/p
32
16. Take input for roll, name ,age and per. condition:
1. roll no has to be a 3 digit no
2. age cannot be <18
3. per >=0 and <=100
def abc():
try:
roll = int(input("Enter roll no :"))
if roll < 100 or roll > 999:
raise ValueError("Invalid roll no, it must be
a 3-digit number.")
abc()
33
O/p
34
17. Write a Python program to connect to a MySQL database and fetch
employee details based on the employee number (empno). Ensure
proper error handling and close the connection after use.
import mysql.connector
from mysql.connector import Error
con = None
try:
con = mysql.connector.connect(host='localhost',
user='root', password='ct', database='employee')
if con.is_connected():
print("Connected")
db = con.cursor()
e = int(input("Enter empno: "))
sql = "SELECT * FROM emp WHERE empno =
{}".format(e)
db.execute(sql)
res = db.fetchall()
for x in res:
print(x)
except Error as e:
print(e)
finally:
if con is not None and con.is_connected():
con.close()
print("Connection closed")
35
18. Write a Python program to connect to a MySQL database and retrieve
employee details based on the employee name. Ensure that the
program handles errors and properly closes the connection after the
operation.
import mysql.connector
from mysql.connector import Error
con = None
try:
con = mysql.connector.connect(host='localhost',
user='root', password='ct', database='employee')
if con.is_connected():
print("Connected")
db = con.cursor()
en = input("Enter name: ")
sql = "SELECT * FROM emp WHERE name =
'{}'".format(en)
db.execute(sql)
res = db.fetchall()
for x in res:
print(x)
except Error as e:
print(e)
finally:
if con is not None and con.is_connected():
con.close()
print("Connection closed")
36
19. Write a Python program to insert multiple rows of employee data
(empno, name, and salary) into an emp table in a MySQL database using
the executemany() method.
import mysql.connector
from mysql.connector import Error
con = None
try:
con = mysql.connector.connect(host='localhost',
user='root', password='ct', database='employee')
if con.is_connected():
print("Connected")
db = con.cursor()
sql = "INSERT INTO emp (empno, name, sal) VALUES
(%s, %s, %s)"
val = [
("101", "amit", "2345"),
("102", "sumit", "1233"),
("103", "kapil", "5432"),
("104", "Mohan", "5555")
]
db.executemany(sql, val)
con.commit()
print(db.rowcount, "records inserted.")
except Error as e:
print(e)
finally:
if con is not None and con.is_connected():
con.close()
print("Connection closed")
37
20. Write a Python program to connect to a MySQL database, retrieve
records of employees based on their name, display them, and then
delete those records from the emp table.
import mysql.connector
from mysql.connector import Error
con = None
try:
con = mysql.connector.connect(host='localhost',
user='root', password='ct', database='employee')
if con.is_connected():
print("Connected")
db = con.cursor()
38
Thank You :)
39