INDEX Merged
INDEX Merged
S. Contents
No.
Python Programs
1 Write a program in Python to input a number from the user and calculate if the given number is
prime or not.
2 Write a program in Python to input a string from the user and find out if the given string is
palindrome or not.
3 Write a program in Python, which inputs a list L of integers and displays the sum of all such integers
from the list L which end with the digit 3.
4 Write a program in Python, which input a list L of numbers and a number to be searched. If the
number exists, it is replaced by 0 and if the number does not exist, an appropriate message is
displayed.
5 Write a Python program, which takes a dictionary Student as input, the dictionary Student
contains Name:(Phy,Chem,Math) as key:value pairs, program should display the average marks
of all students present in the dictionary.
6 Write a Python program to read a text file “POEM.TXT” and print the total number of vowels and
consonants separately present in the text file.
7 Write a Python code to find the size of the file “Notes.txt” in bytes, the number of lines, and
number of words and no. of character.
8 Write a Python program which reads the contents of a text file "BIOPIC.TXT" and displays the
content of the file with every occurrence of the word 'he' replaced by 'she'.
9 Write a Python program to count and display the number of lines starting with ‘A’ (Lower/Upper
both cases) present in the text file “Lines.txt”.
10 Write a Python program to count and display the number of lines that have exactly 5 words in it
present in the text file “Story.txt”.
11 Create a binary file “Student.Dat” with the name and roll number. Search for a given roll number
and
display the name, if not found display appropriate message.
12 Create a binary file “Stud.dat” with roll number, name and marks. Input a roll number and update
details. Create a binary file with roll number, name and marks. Input a roll number and update
details.
1. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
16 Write a program to create a library on your name in python and import it in a program.
17 Write a program which adds any random five even numbers in a list that falls between the highest
and the lowest number. Both highest and lowest numbers are accepted from the user.
19 A school stores records of Class XII students using a list that contains multiple lists as its elements.
The structure of each such element is [Student_Name, Marks, MainSubject].
Crate a complete program using the user-defined functions to perform the operations as
mentioned below:
(a) Push_student(): To push the Student_Name and Marks of all those students, who have
Science as MainSubject, into a Stack StudentInfo
(b) Pop_student(): To delete all items (one at a time) from the stack StudentInfo in LIFO order
and display them. Also display "Empty Stack" when there are no items remaining in the stack.
20 Write a program to connect Python with MySQL using database connectivity and perform the
following operations on data in Database:
A) Create, B) Insert, C) Fetch, D) Update and E) Delete the data.
MySQL Queries
Note: The table contains many more records than shown here. Write the following queries:
(I) To display the total Quantity for each Product, excluding Products with total Quantity less than
5.
(II) To display the orders table sorted by total price in descending order.
(III) To display the distinct customer names from the Orders table.
(IV) Display the sum of Price of all the orders for which the quantity is null.
22 Rahul, who works as a database designer, has developed a database for a bookshop. This
database includes a table BOOK whose column (attribute) names are mentioned below: BCODE:
Shows the unique code for each book.
TITLE: Indicates the book’s title.
AUTHOR: Specifies the author’s name.
PRICE: Lists the cost of the book.
Table: BOOK
24 Write SQL queries for (i) to (iv), which are based on the tables.
i. To display details of all transactions of TYPE Deposit from Table TRANSACT.
ii. To display the ANO and AMOUNT of all Deposits and Withdrawals done in the month of October
2017 from table TRANSACT.
iii. To display the last date of transaction (DOT) from the table TRANSACT for the Accounts having
ANO as 103.
iv. To display all ANO, ANAME and DOT of those persons from tables ACCOUNT and TRANSACT
who have done transactions less than or equal to 3000.
25 Write SQL queries for (i) to (iv), which are based on the tables :
(i) To display the CODE and NAME of all SALESPERSON having “I7” Item Type Code from the
table SALESPERSON.
(ii) To display all details from table SALESPERSON in descending order of SALARY.
(iii) To display the number of SALESPERSON dealing in each TYPE of ITEM.
(Use ITCODE for the same)
(iv) To display NAME of all the salespersons from the SALESPERSON table along with their
corresponding ITEMTYPE from the ITEM table.
Program1:- Write a program in Python to input a number from the user
and calculate if the given number is prime or not.
def calculate_average_marks(student_dict):
for name, marks in student_dict.items():
# Calculate the average of Physics, Chemistry, and Math marks
average_marks = sum(marks) / len(marks)
print(f"Average marks of {name}: {average_marks:.2f}")
# Input: Dictionary of students with their marks in Physics, Chemistry, and Math
student_dict = {}
for _ in range(n):
name = input("Enter student's name: ")
phy = float(input(f"Enter {name}'s marks in Physics: "))
chem = float(input(f"Enter {name}'s marks in Chemistry: "))
math = float(input(f"Enter {name}'s marks in Mathematics: "))
def count_vowels_consonants(filename):
# Initialize vowel and consonant counters
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowel_count = 0
consonant_count = 0
try:
# Open the file
with open(filename, 'r') as file:
# Read the file content
content = file.read()
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
# Call the function with the filename 'POEM.TXT'
filename = "POEM.TXT"
count_vowels_consonants(filename)
OUTPUT
Program7:- Write a Python program to read a text file “Input.txt” and
print the words starting with ‘O’ (Lower/Upper both cases) in reverse
order. The rest of the content is displayed normally.
def process_file(filename):
try:
# Open the file for reading
with open(filename, 'r') as file:
content = file.read()
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
# File name
filename = "Input.txt"
process_file(filename)
OUTPUT
Program8:-Write a Python program which reads the contents of a text
file "BIOPIC.TXT" and displays the content of the file with every
occurrence of the word 'he' replaced by 'she'.
def replace_he_with_she(filename):
try:
# Open the file to read its contents
with open(filename, 'r') as file:
content = file.read()
# Print the modified content (or write back to the file if needed)
print(modified_content)
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
# File name
filename = "BIOPIC.TXT"
replace_he_with_she(filename)
OUTPUT
Program9:- Write a Python program to count and display the number of
lines starting with ‘A’ (Lower/Upper both cases) present in the text file
“Lines.txt”.
def count_lines_starting_with_a(filename):
count = 0
# Open the file in read mode
with open(filename, 'r') as file:
# Loop through each line in the file
for line in file:
# Check if the line starts with 'A' or 'a', considering case-insensitivity
if line.strip().lower().startswith('a'):
count += 1
return count
# If not found
print(f"Student with roll number {search_roll_number} not found.")
# Main execution
filename = "Student.Dat"
create_student_file(filename) # Create the file and populate with data
# Step 1: Create the binary file and populate it with student data
def create_student_file(filename):
with open(filename, 'wb') as file:
# Sample student data (roll_number, name, marks)
students = [
(101, "Alice", 85.5),
(102, "Bob", 90.0),
(103, "Charlie", 78.0),
(104, "David", 92.5),
(105, "Eva", 88.5)
]
if not updated:
print(f"Student with roll number {search_roll_number} not found.")
else:
print(f"Student details updated successfully.")
# Main execution
filename = "Stud.dat"
create_student_file(filename) # Create the file and populate it with student data
import struct
# Encode the book name and author to bytes and pad them to 50 characters
each
book_name_encoded = book_name.encode('utf-8')
book_name_padded = book_name_encoded.ljust(50, b'\0') # Padding with
null bytes
author_encoded = author.encode('utf-8')
author_padded = author_encoded.ljust(50, b'\0') # Padding with null bytes
return count
# Main execution
filename = "Book.dat"
while True:
# Take student details as input
try:
roll_number = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
stream = input("Enter Stream (e.g., Science, Arts, Commerce): ")
percentage = float(input("Enter Percentage: "))
except ValueError:
print("Invalid input. Please enter the correct data types.")
continue
# Function to read and display the data from the CSV file
def read_from_csv(filename):
# Open the file in read mode
with open(filename, mode='r') as file:
reader = csv.reader(file)
# Main execution
filename = 'student.csv'
# Main execution
source_filename = 'Data.csv'
destination_filename = 'Temp.csv'
# Adjust the highest value to the previous even number if it's odd
if highest % 2 != 0:
highest -= 1
# Generate a list of `count` random even numbers within the range [lowest,
highest]
even_numbers = []
while len(even_numbers) < count:
num = random.randint(lowest, highest)
if num % 2 == 0:
even_numbers.append(num)
return even_numbers
# Main execution
def main():
# Accept the lowest and highest numbers from the user
try:
lowest = int(input("Enter the lowest number: "))
highest = int(input("Enter the highest number: "))
# Generate 5 random even numbers between the lowest and highest values
even_numbers = generate_random_evens(lowest, highest)
except ValueError:
print("Invalid input! Please enter valid integers.")
# Function to push customer names into the stack who are staying in 'Delux'
Room Type
def Push_Cust(self, customers):
for customer in customers:
name, room_type = customer
if room_type == 'Delux':
self.stack.append(name)
print(f"Customer '{name}' with 'Delux' Room Type added to the stack.")
# Function to pop customer names from the stack and display them
def Pop_Cust(self):
if len(self.stack) == 0:
print("Underflow: No customers in the stack.")
else:
popped_customer = self.stack.pop()
print(f"Customer '{popped_customer}' has been removed from the stack.")
# Main execution
def main():
# Sample customer records: [Customer_name, Room_Type]
customers = [
["Alice", "Delux"],
["Bob", "Standard"],
["Charlie", "Delux"],
["David", "Standard"],
["Eve", "Delux"]
]
# Push customers who are staying in 'Delux' Room Type onto the stack
hotel_stack.Push_Cust(customers)
# Function to pop all student records from the stack and display them
def Pop_student(self):
if len(self.StudentInfo) == 0:
print("Empty Stack: No students to pop.")
else:
while len(self.StudentInfo) > 0:
student = self.StudentInfo.pop()
print(f"Student '{student[0]}' with marks {student[1]} removed from the
stack.")
# Main execution
def main():
# Sample student records: [Student_Name, Marks, MainSubject]
students = [
["Alice", 85, "Science"],
["Bob", 78, "Commerce"],
["Charlie", 92, "Science"],
["David", 88, "Arts"],
["Eve", 95, "Science"]
]
# A) Create Table
def create_table(connection):
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
student_id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(100) NOT NULL,
student_age INT NOT NULL,
student_grade VARCHAR(10) NOT NULL
)
""")
connection.commit()
print("Table 'students' created successfully.")
# Step 6: Fetch and display all students again to see the update
fetch_students(connection)
# Step 7: Delete a student record
delete_student(connection, 2) # Delete Bob's record