Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

computer assignment (2)

Uploaded by

cvt3zuuuyi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

computer assignment (2)

Uploaded by

cvt3zuuuyi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

ACKNOWLEDGEMENT

I would like to thank my Computer Science teacher, for imparting valuable


suggestions and guidance during the completion of this project. She has
been a source of inspiration and has helped me to understand and
remember important details of this project.

My sincere thanks to our principal, who has so kindly encouraged the


science students to improve their analytical knowledge and skills to find
solutions to the topics concerned.

This project is submitted as a part of the practical examinations included


in the CBSE curriculum for the All India Senior Secondary Certificate
Examination. I would like to thank CBSE for providing us such an
interesting opportunity to explore the practical applications of concepts
while collecting and analyzing the data.

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 Internal Signature of External


Examiner Examiner

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

3. Take input for a number and display its factorial.


Page no-07

4. Count various characters in the string (alphabets, uppercase, lowercase,


digits, spaces, special characters).
Page no-07

5. Write a program to enter name and percentage in a dictionary of n


number of students and display the information.
Page no-08

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

8. Display counts of vowels, consonants, upper, lowercase in a text file.


Page no- 12-13

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

10. Program to implement a stack using a list.


Page no- 17-18

11. TABLE:PRODUCT.
Page no- 19-22

12. Tables: Interiors


Page no- 23-27

13. Write a program to calculate the sum of all the marks given in file
marks.csv. records in the file.
Page no-28

14. Write a program to add/insert records in the file data.csv.


Page no-29

15. Program to write and read details of multiple items to a CSV file
"product.csv".
Page no-30-32

16. Take input for roll, name ,age and per.


Page no-33-34

17. Write a Python program to connect to a MySQL database and fetch


employee details based on the employee number (empno).
Page no-35

4
18. Write a Python program to connect to a MySQL database and retrieve
employee details based on the employee name.
Page no-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.
Page no-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.
Page no-38

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

4. Take input for a number and display its factorial.

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)

print("Total alphabets:", alphabets)


print("Total uppercase:", uppercase)
print("Total lowercase:", lowercase)
print("Total digits:", digits)
print("Total spaces:", spaces)
print("Total special characters:", special)

count()

O/p

8
6. Program to take student details and calculate total, percentage, and
grade based on conditions.

roll = int(input("Enter roll number: "))


name = input("Enter name: ")
m1 = float(input("Enter marks for subj 1: "))
m2 = float(input("Enter marks for subj 2: "))
m3 = float(input("Enter marks for subj 3: "))

total = m1 + m2 + m3
percent = total / 3

if percent >= 90:


grade = "A+"
elif percent >= 80:
grade = "A"
elif percent >= 70:
grade = "B+"
elif percent >= 60:
grade = "B"
elif percent >= 50:
grade = "C"
elif percent >= 40:
grade = "D"
else:
grade = "F"

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()

for char in text:


if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1

if char in vowels:
vowel_count += 1
elif char.isalpha() and char not in vowels:
consonant_count += 1

print("Vowels: ", vowel_count)


print("Consonants: ", consonant_count)
print("Uppercase letters: ", uppercase)
print("Lowercase letters: ", lowercase)
except FileNotFoundError:
print("The file was not found.")

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 = []

with open('student.dat', 'rb') as file:


while True:
try:
student = pickle.load(file)
students.append(student)
if student[0] == roll:
print("Name:", student[1], ", Marks:",
student[2])
flag = 1
except EOFError:
break

14
if flag == 0:
print("Roll number not found.")
return

update_choice = input("Do you want to update marks?


(yes/no): ").lower()
if update_choice == "yes":
new_marks = int(input("Enter new marks: "))
updated_students = []
for student in students:
if student[0] == roll:
student = (student[0], student[1], new_marks)
updated_students.append(student)

with open('student.dat', 'wb') as file:


for student in updated_students:
pickle.dump(student, file)
print("Marks updated successfully.")

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;

CREATE TABLE PRODUCT (


P_ID VARCHAR(5),
PRODUCTNAME VARCHAR(20),
MANUFACTURER VARCHAR(20),
PRICE INT
);
INSERT INTO PRODUCT (P_ID, PRODUCTNAME, MANUFACTURER,
PRICE) VALUES
('TP01', 'POWDER', 'Ponds', 40),
('FW05', 'FACE WASH', 'Himalaya', 45),
('BS01', 'BATH SOAP', 'Himalaya', 55),
('SH06', 'SHAMPOO', 'Dove', 120),
('FW12', 'FACE WASH', 'Dove', 95);

CREATE TABLE CLIENT (


C_ID VARCHAR(2),
CLIENTNAME VARCHAR(20),
City VARCHAR(20),
P_ID VARCHAR(5)
);
INSERT INTO CLIENT (C_ID, CLIENTNAME, City, P_ID) VALUES
('01', 'COSMETIC SHOP', 'Delhi', 'FW05'),
('06', 'TOTAL HEALTH', 'Mumbai', 'BS01'),
('12', 'LIVE LIFE', 'Delhi', 'SH06'),
('15', 'PRETTY WOMAN', 'Delhi', 'FW12'),
('16', 'DREAMS', 'Banglore', 'TP01');

20
/* #1 Display details of clients whose city is "Delhi"*/
SELECT * FROM CLIENT WHERE City = 'Delhi';

/* #2 Display details of products with price in the


range of 50 to 100*/
SELECT * FROM PRODUCT WHERE PRICE BETWEEN 50 AND 100;

/* #3 Display CLIENTNAME, City from CLIENT and


PRODUCTNAME, PRICE from PRODUCT with matching P_ID*/
SELECT CLIENT.CLIENTNAME, CLIENT.City,
PRODUCT.PRODUCTNAME, PRODUCT.PRICE
FROM CLIENT
JOIN PRODUCT ON CLIENT.P_ID = PRODUCT.P_ID;

/* #4 Increase the price of each product by 10*/


UPDATE PRODUCT SET PRICE = PRICE + 10;

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

–- #6 Select manufacturer,max(price),count(*) from


product group by manufacturer;
O/p

–- #7 Select clientname, manufacturer from product,


client where client.p_id=product.p_id;
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
);

-- Creating the 'newones' table


create table newones (
no int primary key,
itemname varchar(50),
type varchar(20),
dateofstock date,
price int,
discount int
);

-- Inserting data into 'interiors' table


insert into interiors values
(1, 'red rose', 'double bed', '2002-02-23', 32000, 15),
(2, 'soft touch', 'baby cot', '2002-01-20', 9000, 10),
(3, 'jerry’s home', 'baby cot', '2002-02-19', 85000, 10),
(4, 'rough wood', 'office table', '2002-01-01', 20000, 20),
(5, 'comfort zone', 'double bed', '2002-01-12', 15000, 20),
(6, 'jerry look', 'baby cot', '2002-02-24', 7000, 19),
(7, 'lion king', 'office table', '2002-02-20', 16000, 20),
(8, 'royal tiger', 'sofa', '2002-02-22', 30000, 25),
(9, 'park sitting', 'sofa', '2001-12-13', 9000, 15),
(10, 'dine paradise', 'dining table', '2002-02-19', 11000,
15);

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';

–- #2 To list the itemname which are priced at more than


10000 from the interiors table.
select * from interiors where type= 'sofa';

–- #3 To list itemname and type of those items, in which


dateofstock is before 22/01/02 from the interiors table
in descending order of itemname.
select itemname, type from interiors where dateofstock <
'2002-01-22' order by itemname desc;

–- #4 To display itemname and dateofstock of those items,


in which the discount percentage is more than 15 from the
interiors table.
select itemname, dateofstock from interiors where
discount > 15;

–- #5 To count the number of items whose type is "double


bed" from the interiors table.
select count(*) from interiors where type = 'double bed';

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;

–- #6 Select avg(discount) from interiors Where


type=‟baby Cot‟;

–- #1 Select 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.")

name = input("Enter Name :")


name = name.upper()

age = int(input("Enter age :"))


if age < 18:
raise ValueError("Invalid Age, it must be >=
18.")
per = float(input("Enter percentage :"))
if per < 0 or per > 100:
raise ValueError("Invalid percentage, it must
be between 0 and 100.")

print("Roll No: ", roll, ", Name: ", name, ",


Age: ", age, ", Percentage: ", format(per, '.2f'))
except ValueError as ve:
print("Error: ", ve)
finally:
print("Finally block always gets executed.")

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()

en = input("Enter name: ")


sql = "SELECT * FROM emp WHERE name=%s"
db.execute(sql, (en,))
res = db.fetchall()

print("Records to be deleted are:")


for x in res:
print(x)
sql = "DELETE FROM emp WHERE name=%s"
db.execute(sql, (en,))
print(db.rowcount, "record deleted.")
con.commit()
except Error as e:
print(e)
finally:
if con is not None and con.is_connected():
con.close()
print("Connection closed")

38
Thank You :)

39

You might also like