Cbse Computer Science
Cbse Computer Science
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
output:
2: writes python function that accepts a string and calculate the no. of uppercase Letters and
Lowercase letters.
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
# Example usage
text = "Hello World! Welcome to Python Programming."
uppercase, lowercase = count_case_letters(text)
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}")
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:
# 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)
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 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
output:
Writing Data:
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 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:
Solution:
Sorted_d = sorted(d.items())
print('Dictionary is ascending order', sorted_d)
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
DESCRIBE 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
Product_id Category
101 Electronices
102 Electronices
103 Electronices
104 Electronices
IV) Retrieve the product_id and Category from the Sales Table
v) Insert one or more rows that will have only Product_id and unit_price
2) Create the following Table “product” and excuse the following Queries:
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);
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
II) Calculate the total reverse generated from all sales in the sales Table
III) Retrieve the sale_id and sale_date from the product_table,filtering the unit_price to
show any values between $60 $2500
421 P3 12000 0
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
II) Write an SQl Query to fetch the count of employees working in project 'P'.
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.
V)Write an SQL Query to display the total salary of each Employeed adding the salary with variable
value .
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.