0% found this document useful (0 votes)
46 views25 pages

Cbse Computer Science

Uploaded by

ravenderider
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)
46 views25 pages

Cbse Computer Science

Uploaded by

ravenderider
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/ 25

1 write a python program to demonstrate the concept of variable length argunment to calculate sum

and product of me first 10 mumbers.

Solution :

def calculate_sum_and_product(*args):
# Calculate sum
total_sum = sum(args)

# Calculate product
total_product = 1
for num in args:
total_product *= num

return total_sum, total_product

# First 10 natural numbers


numbers = tuple(range(1, 11))

# Call the function


sum_result, product_result = calculate_sum_and_product(*numbers)

# Print the results


print(f"The sum of the first 10 numbers is: {sum_result}")
print(f"The product of the first 10 numbers is: {product_result}")

output:

2: writes python function that accepts a string and calculate the no. of uppercase Letters and
Lowercase letters.

Sample String: Python Programming

Solution :

def count_case_letters(input_string):
# Initialize counters
uppercase_count = 0
lowercase_count = 0
# Loop through each character in the string
for char in input_string:
if char.isupper(): # Check if the character is uppercase
uppercase_count += 1
elif char.islower(): # Check if the character is lowercase
lowercase_count += 1

return uppercase_count, lowercase_count

# Example usage
text = "Hello World! Welcome to Python Programming."
uppercase, lowercase = count_case_letters(text)

print(f"Number of uppercase letters: {uppercase}")


print(f"Number of lowercase letters: {lowercase}")

output:

3. Program to input elements in a tuple and to count and display number of even and add numbers
Present init using function.

Solution:

def input_tuple():
"""Function to input elements into a tuple."""
n = int(input("Enter the number of elements in the tuple: "))
elements = []
for _ in range(n):
elem = int(input("Enter an element: "))
elements.append(elem)
return tuple(elements)

def count_even_odd(numbers):
"""Function to count even and odd numbers in a tuple."""
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count

def main():
"""Main function to execute the program."""
print("Input elements into the tuple.")
numbers = input_tuple()
even_count, odd_count = count_even_odd(numbers)
print(f"\nTuple: {numbers}")
print(f"Number of even numbers: {even_count}")
print(f"Number of odd numbers: {odd_count}")

# Execute the program


if _name_ == "_main_":
main()

output:

4. Write a functiom im python to count the no. of lines from a text file "story.txt" which is not
starting with an alphabet "T"

Solution:

def line_count():
file=open("start.txt","w")
file.write("Boy Troy joy goy doy loy isacc verma shastri")

file.close()
file=open("start.txt","r")
count=0
for line in five
if line[0] not in'T':
count + =1
file.close()
print("No of lines not starting with'T'=",count)
Line_count()

Output:

5: write a program to open a python file "abc.txt” to write a paragraph. Them display the current
Position of the file pointer. Move the file pointer by 10 bits , and display rest of the convent

Solution:

# Open the file in write mode and write a paragraph


with open("myfile.txt", "w") as file:
file.write("This is a sample paragraph. It is written to demonstrate file
operations in Python.")

# Open the file in read mode


with open("myfile.txt", "r") as file:
# Display the current position of the file pointer
print("Initial file pointer position:", file.tell())

# Move the file pointer to the 10th byte


file.seek(10)
print("File pointer position after seeking:", file.tell())

# Read and display the rest of the contents from the current position
content = file.read()
print("Remaining contents of the file:\n", content)

output:
6: write a python program to count words ending with alphabet "e" image text file "article.txt"

Solution:

def count-words():
file = open("article.txt", "w")
file write("eshe cow Dog ee cie guide")
file. Close()
file = Open ("article.txt", "r")
count = 0
data = file.read()
words = data.split()
for w and in wards:
if word [-1] = = 'e':
Count += 1
Print (count)
fie.close()
count.words()

output:

7:A Binary file “Book.dat”has structure [BookNo,BookName, Author,Price] write a user program
containing defined function create file() .to input data for a records and add to Book.dat

Solution:

import pickle

def create_file():
"""
Creates a binary file named 'Book.dat' and allows the user to add book
records.
Each record has the structure: [Book No, Book Name, Author, Price].
"""
try:
with open("Book.dat", "wb") as file:
n = int(input("Enter the number of books to add: "))
books = []
for _ in range(n):
book_no = int(input("Enter Book No: "))
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Book Price: "))
books.append([book_no, book_name, author, price])
pickle.dump(books, file)
print(f"{n} records successfully added to 'Book.dat'.")
except Exception as e:
print("An error occurred:", e)

# Call the function


create_file()

output:

8: A binary file "Book.dat" has structure [BookNo, Book Name, Author, Price].

i) write a user defined function Create File) to Input date for a record and add to
BOOK.dat
ii) ii) write a function Count Rec (Author) in python Which accepts the Author name as
parameter and count and return no of Books by the given author.

Solution :

import pickle

def create file():


file=open(book.dat",ab")
BookNo=int(input("Enter book number:"))
Book_Name= input("Enter Book name:")
Author = input("Enter Author:")
price=int(input("Enter price:"))
record=[Book_No,Book_Name,Author,price]
pickle.dump(record,file)
file.close()

def count Rec(Author)


file=open(book.dat","rb")
count=0;
try:
while True:
record=pickle.load(file)
if record[2]== Author:
count + =1;
except Eoe Error:pass
return count
file.close()

def testprogram():
while True:
create file()
choice=input("Add more record(y/n)?")
if choice in 'Nn':
break
Author= input ("Enter authorname to search")
n= countRec(Author)
print("No of Books are",n)

text program();

output:

9: Write a Python program to Write a Python list to a csv file.After writing the csv file read the csv
file and display the content:

Solution:

import csv

# Define a list of data


data = [
["Book No", "Book Name", "Author", "Price"],
[101, "Python Programming", "John Doe", 350.50],
[102, "Data Science Basics", "Jane Doe", 450.75],
[103, "Machine Learning", "Alice Smith", 500.00]
]

# Write the list to a CSV file


csv_file = "books.csv"
try:
with open(csv_file, "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print(f"Data written successfully to {csv_file}")
except Exception as e:
print("An error occurred while writing to the CSV file:", e)

# Read the CSV file and display its content


try:
with open(csv_file, "r") as file:
reader = csv.reader(file)
print("\nContents of the CSV file:")
for row in reader:
print(row)
except Exception as e:
print("An error occurred while reading the CSV file:", e)

output:

Writing Data:

Data Written successfully to books.csv

10: Write a program to write and read employee records in a binary file named "employee. dat".
Also demonstrate he size of the five.

Solution:

import pickle
print("working with Binary files")
B file = open ("empfile.dat",ab)
rec no = 1
print("Enter Records of Employees")
print()
while true:
print("Record no",recno)
ebasic=int(input("\tBasic salary:"))
eno = int (imput("It Employee mumber: "))
ename = imput("It Employee Name: ")
allow int (imput("It Allowances!"))
total beslet allow.
Print("It Total galany", torsul)
edata= [eno, emame, ebasic, allow, total]
pickle.dump(edata,b file)
ans= input("Do you wish enter more records(y\n)")
recno = rec no +1
if ans. lower() == 'n';
Print (Record entry OVER")
print()
break
print("size of binary file cdn Bytes):", bfile.teu())
bfile.close()
print("Now reading the employee records from the file")

print()
readrec= 1;
try:
with open ("enfile.dat","rb")as bfive:
while true:
edata=pickle.load(bfile)
print(edata)
readrec=readrec+1
except Eof Error;
pass
bfile.close()

output:
11: Program to store and display multiple integers in and from a binary file

Solution:

def binfile():
import pickle
file =open('data.dat','wb')
while true:
x = int(intput("Enter the integer:"))
pickle.dump(x,file)
ansc= intput('Do you want to enter more data y\n:')
if ans.upper =='N':break
file.close()
file = open('data.dat','rb')
try:
while true:
y=pickle.load(file)
print(y)
except Eof Error:
pass
file.close()
binfile()

output:
12: Write a menu driven program

If you press 1:it will reverse the numbers

If you press 2: it will check the no is palindrome or not

If you press 3: it will show the sum of the digits of the numbers

Solution:

while true :
print("1.Reverse the number")
print("2.To check the number is palindrome or not")
print("3.give the sum of the digits of the numbers")
choice= int (intput("Enter thr choice"))
if choice ==1:
num = int(input("Enter the numbers"))
rev = 0
while num 1 = 0;
digits = num % 0;
rev = rev * 10 digits
print("reversed =",rev)
if choice ==2:
n=int(input("Enter the number"))
temp = n
rev = 0
while (n>0)
dig = n % 10
rev = rev * 10 + dig
n = n//10
if(temp == rev);
print("palindrome")
else :
print ("Not palindrome")
if choice == 3:
n = int (input("Enter the number"))
sum =0
for dig in str (n)
sum + = int (dig)
print("sum = ",sum)

output:

13: Write a program to check a number is Buzz number or not (A buzz number is a number which has
7 at a unit digits of the number is visible by 7

Solution:

def is BUzz(num):
return (num % 10==7 or num % 7 ==0)
j=int(input("Enter any number"))
if (is buzz(i)):
print("Buzz number")
else:
print("Not a Buzz Number")

output:
14: Print a Dictionary where the keys are numbers between 1and 15 and the values are square of
keys

Solution:

Dict = {}
for i in range(15):
j= i**2
Dict[i] =j

print(Dict)

output:

15: Write a program to sort (Assending or Decending ) a dictionary by value

Solution:

d= {1:2, 3:4, 4:3, 2:1, 0:0}


print('original Dictionary: ',d)

Sorted_d = sorted(d.items())
print('Dictionary is ascending order', sorted_d)

Sorted_dl = sorted(ditems(), reverse=true))


print('Dictionary in Decending order',sorted_dl)

output:
SQL
QUERIES
Sale
Product_id Product_name category Unit _price
101 Laptop Electronics 500
102 Smartphone Electronics 300
103 Headphones Electronics 30
104 Keyboard Electronics 20
105 Mouse Electronics 15

1:Create the following Table named "sales" and execute me following queries

CREATE DATABASE S1;


USE S1;
CREATE TABLE Sales (
Product id INT (5) PRIMARY KEY,
Product name VARCHAR (100),
Category VARCHAR (50),
Unit-Price DECIMAL (10, 2)
);

DESCRIBE Sales;

INSERT INTO Product (product_id, produt name, category, Unit_price)


VALUES(101) (Laptop', 'Electronices,500.00),
(102, 'Smartphone!, 'Electronices',300.00),
(103, "Headphones", Electronices, 30.00),
(104, 'Keyboard', 'Electronices', 20.00),
(105) 'Mouse', 'Electronices',15.00);

SELECT FROM sales;


Product_id Product_name Category Unit_price

101 Laptop Electronices 500

102 Smartphones Electronices 300

103 Headphones Electronices 30

104 Keyboard Electronices 20

101 Laptop Electronices 500

102 Smartphones Electronices 300

103 Headphones Electronices 30

104 Keyboard Electronices 20

105 Mouse Electronices 15

106 Smartphone Electronices 300

107 Laptop Electronices 500

I) Retrieve all columns from the sales Table


SELECT * FROM Sales ;

II) Filter the products Table to show any products in the ‘Electronices’ category
SELECT * FROM Sales WHERE Category =’Electronices’;
III) Filter the Sales Table to show any Sales with a total price greater then $100

SELECT* FROM SALES WHERE UNIT_PRICE > 100 ;

Product_id Category

101 Electronices

102 Electronices

103 Electronices

104 Electronices

Product_id Product_name Category Unit_price

101 Laptop Electronices 500

102 Smartphones Electronices 300

103 Headphones Electronices 30

104 Keyboard Electronices 20

105 Mouse Electronices 15

106 NULL NULL 800

107 NULL NULL 500


Product_id Product_name Category Unit_price
101 NULL NULL 800
102 Laptop Electronices 300
103 NULL NULL 500
104 Smartphones Electronices 300
105 Headphones Electronices 30
106 Keyboard Electronices 20
107 Mouse Electronices 15

IV) Retrieve the product_id and Category from the Sales Table

SELECT Product_id , Category FROM Sales;

v) Insert one or more rows that will have only Product_id and unit_price

INSERT INTO Sales (Product_id, unit_price)


VALUES(108, 500.00);

VI) Arrange the records of the table in decending order of unit_price

SELECT *FROM Products ORDER BY unit_price DESC;

Sales_id Product_id Quality_sold Sale_date Total_price


1 101 5 2024-01-01 2500
2 102 3 2024-01-02 900
3 103 2 2024-01-02 60
4 104 4 2024-01-03 80
5 105 6 2024-01-03 90

2) Create the following Table “product” and excuse the following Queries:

CREATE DATABASE product;


Use product;

CREATE TABLE Product(


Sale_id INT(3)PRIMARY KEY,
Product_id INT(3)
Quantity sold INT(3)
Sale_date DATE,
Total_price INT(10)
);

DESCRIBE Product
INSERT INTO Product (Sale_id,product_id,Quantity_sold,Sale_date,total_price)VALUES
(1,101,5,’2024-01-01’,2500),
(2,102,3,’2024-01-02’,900),
(3,103,2,’2024-01-02’,60);
(4,104,4,2024-01-03’,80);
(5,105,6,’2024-01-03’,90);

SELECT * FROM Product;

Sale_id Total_price

4 80

5 90
Total_revenue

3630

Sale_id Sale_date
2 2024-01-02
3 2024-01-02
4 2024-01-03
5 2024-01-03

I) Retrieve the sale_id and total_price from the sales Table for Sales made on January 3
,2024

SELECT Sale_id,total_price,FROM Product WHERE Sale_date, ‘2024-01-03’;

II) Calculate the total reverse generated from all sales in the sales Table

SELECT SUM (total_price) AS Reverse FROM Product;

III) Retrieve the sale_id and sale_date from the product_table,filtering the unit_price to
show any values between $60 $2500

SELECT Sale_id,Sale_date, From WHERE Total_price BETWEEN 60 AND 900;

Sale_id Product_id Quantity_sold Sale_date Total_price Customer_id


1 101 5 2024-01-01 2500 NULL
2 102 3 2024-01-02 900 NULL
3 103 2 2024-01-02 60 NULL
4 104 4 2024-01-03 80 NULL
5 105 6 2024-01-03 90 NULL
Sale_id Product_id Quantity_sold Sale_date Total_price
1 101 5 2024-01-01 2500
2 102 3 2024-01-02 900
3 103 2 2024-01-02 60
4 104 4 2024-01-03 80
5 105 6 2024-01-03 90

Sale_id Product_id Quantity_sold Sale_date Total_price


1 101 5 2024-01-01 2500
2 102 3 2024-01-02 900
3 103 2 2024-01-02 60
5 105 6 2024-01-03 90

IV) ADD or more column named customer _id in the table

ALTER TABLE Product


ADD COLUMN Customer_id INT (3);
SELECT* FROM product;

V) Delete the column Customer_ID


ALTER TABLE Product
DROP COLUMN Customer_id;
SELECT *FROM product;

VI) Delete the now where Product_ id is 104


DELETE FROM product WHERE product_id=104;
SELECT* FROM PRODUCT;

Emp_id project salary variable

121 P1 8000 500

321 P2 10000 1000

421 P3 12000 0

3) create he following Table "EmployeeSalary" and execure the following quentes

CREATE DATABASE Employee3;


USE Employee3;
CREATE TABLE Employee Salary (
Empid INT (3) PRIMARY KEY,
Presect VARCHAR (2),
Salary INT(5),
Variable INT(5)
);

DESCRIBE Employee Salary;

INSERT INTO Eamplayce salary (Empid, projet, Sarany, Venialbl


VALUES (121, 'p1', 8000, 500),
(30), 'P2', 18000, 1000),
(421, 'p1', 12000, 0);

SELECT *FROM Employee Salary;

Project
P1
P2
P3

Count(*)

P3 1 12000

P2 1 10000

P1 1 8000

I)Write an SQL Query to fetch the different project available from the Employee Salary Table

SELECT DISTINCT (Project) FROM Employee Salary;

II) Write an SQl Query to fetch the count of employees working in project 'P'.

SELECT COUNT(*) FROM Employee Salary WHERE Project = 'P';


Ⅲ) Write an SQL Query to fetch the Project-wise count of employees started by Project's
count in Descendiing order

SELECT Project, COUNT (Empid) Empcount FROM Employee Salary GROUP BY Project
ORDER BY Empcount DESC;

MAX MIN

12000 8000

Empid Total

121 8500

321 11000

421 12000

Empid Salary

321 10000

421 12000

Empid Project

321 P2

421 P3

IV)Write an SQL Query to find the maximum ,minimum and Average salary of the Employee.

SELECT MAX(Salary),MIN(Salary),Avg(Salary) From Emplyoee Salary;

V)Write an SQL Query to display the total salary of each Employeed adding the salary with variable
value .

SELECT Empid ,salary +variable As Total From Emplyoee Salary;

VI)Write an SQL Query to find the employee id whose Salaryies in the range of 9000 and 15000.
SELECT Empid,Salary FROM EmplyoeeSalary WHERE Salary BETWEEN 9000 AND 15000;

VII)Write an SQL Query to fetch all those emplyoees who work on projects other than p.

SELECT Empid,project FROM Emplyoee Salary WHERE NOT project = ‘p1’;

You might also like