Pranjal
Pranjal
(2023-25)
COMPUTER
SCIENCE(08
3)
SUb
REPORT FILE
Submitted by : Pranjal Srivastava
Class : XII S4
INDEX
S. CONTENT PAGE
NO. NO.
1. REVIEW OF PYTHON BASICS 3-14
11. Menu driven programme for even number odd number and 16-18
number with series
18 Write a programme to read data from text file and display 34-35
number of Vowels and constant
30 BIBLIOGRAPHY
Table of Contents
1 .Review of python basics 3-14
1.1Program to check if a number is prime or not
2 .FUNCTIONS 15-32
2.1Menu driven programme for even number odd number and number with series
2.3Write a programme using functions to calculate simple interest compound interest and emi for a plan
2.4Calculate area of different shapes circle I square a rectangle a parallelogram and trapezium
2.5Python programme to count following forgiveness number of alphabets number of words number of
vowels frequency of characters
3.1.4Write a python programme with function to read the text file data.txt and display those words
which have less than four characters
3.3.1Write user defined function to perform read and write operations on to a “student.csv” file
having fields roll number name stream and marks
4.STACK 53-57
4.1Write menu based programme to add delete and display the record of hostel using list as stack
Menu driven programme to demonstrate four major operations performed on a table through my
sql python connectivity
REVIEW OF
PYTHON
BASICS
# Program to check if a number is prime or not
Output
# Python program to check if the number is an
Armstrong number or not
Output
#PYTHON PROGRAM TO CHECK IF NUMBER IS
PALINDROME OR NOT
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!”)
Output
# PYTHON PROGRAM FOR FIBBONACCI SERIES
n = int(input("Enter the number of terms for the Fibonacci series: "))
a, b = 0, 1
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Fibonacci series up to", n, "terms:")
print(a)
else:
print("Fibonacci series up to", n, "terms:")
print(a, b, end=" ")
for _ in range(2, n):
next_term = a + b
print(next_term, end=" ")
a, b = b, next_term
Output
#PYTHON PROGRAM FOR TRIBBONACCI SERIES
Output
# PYTHON PROGRAM FOR BINARY TO DECIMAL
CONVERSION
Output
# PYTHON PROGRAM FOR DECIMAL TO OCTAL
CONVERSION
decimal = int(input("Enter a decimal number: "))
# Initialize variables
octal = ""
# Handle the special case of 0
if decimal == 0:
octal = "0"
else:
# Convert decimal to octal
while decimal > 0:
remainder = decimal % 8
octal = str(remainder) + octal
decimal = decimal // 8
print(f"The octal equivalent is: {octal}")
Output
# PROGRAM FOR DICE
import random
while True:
input("Press Enter to roll the dice...")
result = random.randint(1, 6)
print(f"You rolled a {result}")
play_again = input("Do you want to roll again? (yes/no): ").lower()
if play_again != "yes":
break
Output
#PYTHON PROGRAM FOR SERIES 1 TO 20
Output
FUNCTIONS
# MENU DRIVEN PROGRAMME FOR EVEN NUMBER
ODD NUMBER AND NUMBER WITH SERIES
while True:
print("Menu:")
print("1. Check if a number is even or odd")
print("2. Generate a series of numbers")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
number = int(input("Enter a number: "))
result = is_even_or_odd(number)
print(f"{number} is an {result} number.")
elif choice == '2':
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
series = generate_series(start, end)
print("Series of numbers:", series)
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3).")
Output
#MENU DRIVEN PROGRAMME TO CONVERT CASE OF
GIVEN TEXT AS USERS CHOICE
while True:
print("Menu:")
print("1. Convert text to Sentence Case")
print("2. Convert text to lowercase")
print("3. Convert text to UPPERCASE")
print("4. Convert text to Title Case")
print("5. Exit")
if choice == '1':
text = input("Enter text to convert to Sentence Case: ")
result = to_sentence_case(text)
print("Converted text:", result)
elif choice == '2':
text = input("Enter text to convert to lowercase: ")
result = to_lower_case(text)
print("Converted text:", result)
elif choice == '3':
text = input("Enter text to convert to UPPERCASE: ")
result = to_upper_case(text)
print("Converted text:", result)
elif choice == '4':
text = input("Enter text to convert to Title Case: ")
result = to_title_case(text)
print("Converted text:", result)
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5).")
Output
#WRITE A PROGRAMME USING FUNCTIONS TO
CALCULATE SIMPLE INTEREST COMPOUND INTEREST
AND EMI FOR A PLAN
print("\nResults:")
print(f"Simple Interest (SI): {si:.2f}")
print(f"Compound Interest (CI): {ci:.2f}")
print(f"Monthly Installment (MI): {mi:.2f}")
Output
# CALCULATE AREA OF DIFFERENT SHAPES CIRCLE I
SQUARE A RECTANGLE A PARALLELOGRAM AND
TRAPEZIUM
import math
while True:
print("Menu:")
print("1. Calculate the area of a circle")
print("2. Calculate the area of a square")
print("3. Calculate the area of a rectangle")
print("4. Calculate the area of a parallelogram")
print("5. Calculate the area of a trapezium")
print("6. Exit")
if choice == '1':
radius = float(input("Enter the radius of the circle: "))
area = calculate_circle_area(radius)
print(f"The area of the circle is {area:.2f} square units.")
elif choice == '2':
side_length = float(input("Enter the side length of the square: "))
area = calculate_square_area(side_length)
print(f"The area of the square is {area:.2f} square units.")
elif choice == '3':
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = calculate_rectangle_area(length, width)
print(f"The area of the rectangle is {area:.2f} square units.")
elif choice == '4':
base = float(input("Enter the base of the parallelogram: "))
height = float(input("Enter the height of the parallelogram: "))
area = calculate_parallelogram_area(base, height)
print(f"The area of the parallelogram is {area:.2f} square units.")
elif choice == '5':
base1 = float(input("Enter the first base of the trapezium: "))
base2 = float(input("Enter the second base of the trapezium: "))
height = float(input("Enter the height of the trapezium: "))
area = calculate_trapezium_area(base1, base2, height)
print(f"The area of the trapezium is {area:.2f} square units.")
elif choice == '6':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5/6).")
Output
#PYTHON PROGRAMME TO COUNT FOLLOWING
FORGIVENESS NUMBER OF ALPHABETS NUMBER OF
WORDS NUMBER OF VOWELS FREQUENCY OF
CHARACTERS
while True:
print("Menu:")
print("1. Count the number of alphabets")
print("2. Count the number of words")
print("3. Count the number of vowels")
print("4. Calculate the frequency of characters")
print("5. Exit")
if choice == '1':
count = count_alphabets(text)
print(f"Number of alphabets: {count}")
elif choice == '2':
count = count_words(text)
print(f"Number of words: {count}")
elif choice == '3':
count = count_vowels(text)
print(f"Number of vowels: {count}")
elif choice == '4':
frequency = character_frequency(text)
print("Frequency of characters:")
for char, count in frequency.items():
print(f"{char}: {count} times")
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5).")
OUTPUT
File handling
TEXT FILE
def count_vowels_and_consonants(filename):
try:
with open(filename, ‘r’) as file:
text = file.read()
vowels = “AEIOUaeiou”
vowel_count = 0
consonant_count = 0
except FileNotFoundError:
print(“File not found.”)
except Exception as e:
print(“An error occurred:”, str©)
# Example usage:
# Replace ‘your_text_file.txt’ with the name of your text file.
Count_vowels_and_consonants(‘para.txt’)
Output
def find_max_min_word(filename):
try:
with open(filename, ‘r’) as file:
text = file.read()
words = text.split()
if not words:
print(“The file is empty.”)
return
max_word = min_word = words[0]
for word in words:
if len(word) > len(max_word):
max_word = word
if len(word) < len(min_word):
min_word = word
print(f”Word with the maximum characters: {max_word}”)
print(f”Word with the minimum characters: {min_word}”)
except FileNotFoundError:
print(“File not found.”)
except Exception as e: print(“An error occurred:”, str©
find_max_min_word(‘your_text_file.txt’)
Output
#WRITE A PYTHON PROGRAMME WITH FUNCTION TO
FILTRE (OLD FILE ,NEW FILE) THAT COPIES ALL THE
LINES OF A TEXT FILE “SOURCE.TXT” ONTO
“TARGET.TXT” EXCEPT THOSE LINES WHICH START
WITH “@” SIGN
def filter_and_copy_lines(source_file, target_file):
try:
with open(source_file, ‘r’) as source, open(target_file, ‘w’) as target:
for line in source:
if not line.startswith(‘@’):
target.write(line)
print(“Filtered and copied successfully.”)
except FileNotFoundError:
print(“File not found.”)
except Exception as e:
print(“An error occurred:”, str©)
filter_and_copy_lines(‘source.txt’, ‘target.txt’)
Output
#WRITE A PYTHON PROGRAMME WITH
FUNCTION TO READ THE TEXT FILE
DATA.TXT AND DISPLAY THOSE WORDS
WHICH HAVE LESS THAN FOUR CHARACTERS
def display_short_words(filename):
try:
with open(filename, ‘r’) as file:
text = file.read()
words = text.split()
short_words = [word for word in words if len(word) <4]
print(“Words with less than four characters:”)
for word in short_words:
print(word)
except FileNotFoundError:
print(“File not found.”)
except Exception as e:
print(“An error occurred:”, str©)
display_short_words(‘para.txt’)
Output
BINARY FILE
import pickle
def addrec():
l=[]
f=open(“data.dat”,”ab”)
rn=int(input(“enter room number”))
pr=int(input(“enter the price of room”))
rt=input(“enter the type of room”)
l=[rn,pr,rt]
pickle.dump(l,f)
print(“record added in the file”)
f.close()
addrec()
def disp():
try:
f=open(“data.dat”,”rb”)
while true:
d=pickle.load(f)
print(d)
except:
f.close()
disp()
def specific_rec(rno):
try:
f1=open(“data.dat”,”rb”)
while true:
d=pickle.load(f1)
if rno==d[0]:
print(d)
except:
f1.close()
try:
file=open(“data.dat”,”rb”)
f=open(“temp1.dat”,”wb”)
while true:
d=pickle.load(file)
if roll==d[0]:
d[1]=int(input(“enter modified price”))
d[2]=input(“enter modified room type”)
pickle.dump(d,f)
except:
print(“record updated”)
file.close()
f.close()
os.remove(“data.dat”)
os.rename(“temp1.dat”,”data.dat”)
mod()
import os
def delete():
roll=int(input(“enter room no. whose record you want to delete”))
try:
file=open(“data.dat”,”rb”)
f=open(“temp1.dat”,”wb”)
while true:
d=pickle.load(file)
if roll!=d[0]:
pickle.dump(d,f)
else:
found=1
except:
print(“record deleted”)
file.close()
f.close()
os.remove(“data.dat”)
os.rename(“temp1.dat”,”data.dat”)
delete()
Output
CSV FILE
#Write user defined function to perform read and write operations on to a
“student.csv” file having fields roll number name stream and marks
import csv
def read_student_data(file_name):
student_data = []
try:
with open(file_name, mode=’r’, newline=’’) as file:
csv_reader = csv.DictReader(file)
for row in csv_reader:
student_data.append(row)
except FileNotFoundError:
print(f”File ‘{file_name}’ not found.”)
return student_data
while True:
roll_number = input(“Enter Roll Number (or type ‘done’ to finish): “)
if roll_number.lower() == ‘done’:
break
name = input(“Enter Name: “)
stream = input(“Enter Stream: “)
marks = input(“Enter Marks: “)
records.append({‘roll_number’: roll_number, ‘name’: name, ‘stream’:
stream, ‘marks’: marks})
while True:
print(“\nCSV File Menu:”)
print(“1. Write a Single Record”)
print(“2. Write All Records”)
print(“3. Exit”)
if choice == “1”:
write_single_record()
else:
print(“Invalid choice. Please select a valid option.”)
Output
Stack
#WRITE MENU BASED PROGRAMME TO ADD DELETE
AND DISPLAY THE RECORD OF HOSTEL USING LIST AS
STACK
def add_record(stack, record):
stack.append(record)
print(“Record added successfully.”)
def delete_record(stack):
if not stack:
print(“The stack is empty. No records to delete.”)
else:
removed_record = stack.pop()
print(f”Record removed: {removed_record}”)
def display_records(stack):
if not stack:
print(“The stack is empty. No records to display.”)
else:
print(“Records in the stack:”)
for record in stack:
print(f”Hostel Number: {record[0]}, Total Students: {record[1]}, Total
Rooms: {record[2]}”)
hostel_records = []
while True:
print(“Menu:”)
print(“1. Add a record”)
print(“2. Delete the top record”)
print(“3. Display all records”)
print(“4. Exit”)
if choice == ‘1’:
hostel_number = input(“Enter Hostel Number: “)
total_students = input(“Enter Total Students: “)
total_rooms = input(“Enter Total Rooms: “)
record = (hostel_number, total_students, total_rooms)
add_record(hostel_records, record)
elif choice == ‘2’:
delete_record(hostel_records)
elif choice == ‘3’:
display_records(hostel_records)
elif choice == ‘4’:
print(“Goodbye!”)
break
print(“Invalid choice. Please select a valid option (1/2/3/4).”)
Output
SQL QUERIES
(1) Create table a school bus (rt no integer(20), area covered
varchar(), Capacity integer(20), Noofstudents Integer(), transporter
integer(), charges integer):
(2) Desc school bus;
(3) Insert into schoolbus
values(1,’vasantkunj’,100,120,10,’shivam travels’,100000);
(4) Select * from schoolbus;
(5) Select * from SchoolBus order by Rtno where Capacity >
Noofstudent;
(6) Select Area_cover from SchoolBus where Distance > 20 and
Charges < 80000 ;
(7) SELECT TRANSPORTER , SUM(NoOfStudents) FROM SCHOOLBUS
GROUP BY TRANSPORTER;
(8) Select rtno , area_covered , Charges / Noofstudent as Average
from SchoolBus ;
(9) Insert into SchoolBus values (11, "Motibagh", 35, 32, 10, "kisan
tours", 35000) ;
(10) Select sum(distance) from school bus where transporter= "Yadav
travels";
(11) Select min(no of students) from school bus;
(12) Select avg(charges) from school bus where transporter = "Anand
travels";
(13) Select distinct transporter from school bus;
(14)select * from schoolbus order by area_covered;
(15) update sschoolbus set distance=’30’ where
area_covered=’janakpuri’;
(16) delete from schoolbus where area_covered=’janakpuri’;
Rtn Area_Cover Capaci NoofStude Distan Transport Charg
o ed ty nts ce er es
Shivam
1 Vasant Kunj 100 120 10 travels 100000
Anand
2 Hauz Khas 80 80 10 travels 85000
Anand
3 Pitampura 60 55 30 travels 60000
Anand
4 Rohini 100 90 35 travels 100000
Yamuna Bhalla
5 Vihar 50 60 20 travels 55000
Krishna Yadav
6 Nagar 70 80 30 travels 80000
Yadav
7 Vasundhara 100 110 20 travels 100000
Paschim Speed
8 Vihar 40 40 20 travels 55000
Speed
9 Saket 120 120 10 travels 100000
Kisan
10 Janakpuri 100 100 20 Tours 95000
PYTHON SQL
CONNECTIVITY
#MENU DRIVEN PROGRAMME TO DEMONSTRATE
FOUR MAJOR OPERATIONS PERFORMED ON A TABLE
THROUGH MY SQL PYTHON CONNECTIVITY
• import qrcode
• import sqlite3
• # Establishing SQLite connection
• conn = sqlite3.connect('qrcode_data.db')
• cursor = conn.cursor()
• # Creating a table to store QR code data
• cursor.execute('''CREATE TABLE IF NOT EXISTS qr_codes
• (id INTEGER PRIMARY KEY AUTOINCREMENT,
• data TEXT NOT NULL,
• file_name TEXT NOT NULL)''')
• conn.commit()
• def generate_qr_code(data, file_name):
• qr = qrcode.QRCode(version=1, box_size=10, border=4)
• qr.add_data(data)
• qr.make(fit=True)
• qr_img = qr.make_image(fill_color="black",
back_color="white")
• qr_img.save(file_name)
• print(f"QR code generated and saved as {file_name}")
• def save_qr_code_data(data, file_name):
• cursor.execute("INSERT INTO qr_codes (data, file_name)
VALUES (?, ?)", (data, file_name))
• conn.commit()
• print("QR code data saved successfully.")
• def display_qr_code_data():
• cursor.execute("SELECT * FROM qr_codes")
• qr_codes = cursor.fetchall()
• if qr_codes:
• print("QR code data:")
• for qr_code in qr_codes:
• print(f"ID: {qr_code[0]}, Data: {qr_code[1]}, File Name:
{qr_code[2]}")
• else:
• print("No QR code data found.")
• while True:
• print("Menu:")
• print("1. Generate QR code")
• print("2. Save QR code data")
• print("3. Display QR code data")
• print("4. Exit")
• choice = input("Enter your choice (1-4): ")
• if choice == "1":
• data = input("Enter the data for the QR code: ")
• file_name = input("Enter the file name to save the QR code
(with extension): ")
• generate_qr_code(data, file_name)
• elif choice == "2":
• data = input("Enter the data name to save: ")
• file_name = input("Enter the file name associated with the
data: ")
• save_qr_code_data(data, file_name)
• elif choice == "3":
• display_qr_code_data()
• elif choice == "4":
• break
• else:
• print("Invalid choice. Please try again.")
• # Closing the SQLite connection
• conn.close()