comp2
comp2
comp2
Roll-30
Section-B(SCIENCE)
Subject-computer
Seasion-2024-25
1.Write a program in Python to enter a given
temperature in Celsius nto Fahrenheit with the help
of a user defined function.
def convert_to_24_hour_format(time_12hr):
period = time_12hr[-2:].upper()
hour = int(time_12hr[:2])
minute = time_12hr[3:5]
if period == 'AM':
if hour == 12:
hour = 0
return f"{hour:02}:{minute} AM"
elif period == 'PM':
if hour != 12:
hour += 12
return f"{hour:02}:{minute} PM"
else:
return "Wrong peroid format entered."
time_12hr = input("Enter time in 12-hour format (HH:MM
AM/PM): ")
time_24hr = convert_to_24_hour_format(time_12hr)
print("Time in 24-hour format:", time_24hr)
PROGRAM3
def replace_vowels(input_string):
vowels = "AEIOUaeiou"
result = ""
for char in input_string:
if char in vowels:
result += "@"
else:
result += char
return result
user_string = input("Enter a string: ")
modified_string = replace_vowels(user_string)
print("Modified string:", modified_string)
PROGRAM4
def print_diamond_pattern(n):
for i in range(n):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
for i in range(n - 2, -1, -1):
print(" " * (n - i - 1) + "*" * (2 * i + 1))
rows = int(input("Enter the number of rows for the
diamond pattern: "))
print_diamond_pattern(rows)
PROGRAM5
def fibonacci_series(n):
a, b = 0, 1
series = []
for _ in range(n):
series.append(a)
a, b = b, a + b
return series
num_terms = int(input("Enter the number of terms for
the Fibonacci series: "))
fib_series = fibonacci_series(num_terms)
print("Fibonacci series:", fib_series)
PROGRAM6
def login(a,b):
name="admin"
password="123"
if a == name and b == password:
print("Login successful! Welcome,", username)
elif a == name and b != password:
print("Login failed. Incorrect password.")
elif a != name and b == password:
print("Login failed. Incorrect username.")
else:
print("Login failed.")
username=input("Enter your username: ")
user_password = input("Enter your password: ")
login(username,user_password)
PROGRAM7
import math
def calculate_sin(x,n):
x = math.radians(x)
sin_x = 0
for i in range(n):
term = ((-1)*i * x*(2 * i + 1)) / math.factorial(2 * i + 1)
sin_x += term
return sin_x
angle = float(input("Enter the angle in degrees: "))
terms = int(input("Enter the number of terms for the
Taylor series: "))
sin_value = calculate_sin(angle, terms)
print(f"The approximate value of sin({angle}) using
{terms} terms is: {sin_value}")
PROGRAM8
import random
def roll_dice():
return random.randint(1, 6)
dice_roll = roll_dice()
print("You rolled:", dice_roll)
PROGRAM9
def is_palindrome(number):
return str(number) == str(number)[::-1]
def is_armstrong(number):
num_digits = len(str(number))
sum_of_powers = sum(int(digit) ** num_digits for digit
in str(number))
return sum_of_powers == number
def main():
while True:
print("\nMenu:")
print("1) Check if a number is palindrome")
print("2) Check if a number is Armstrong")
print("3) Exit")
choice = input("Enter your choice (1, 2, or 3): ")
if choice == "1":
number = int(input("Enter a number to check if
it's a palindrome: "))
if is_palindrome(number):
print(f"{number} is a palindrome.")
else:
print(f"{number} is not a palindrome.")
elif choice == "2":
number = int(input("Enter a number to check if
it's an Armstrong number: "))
if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
elif choice == "3":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
main()
PROGRAM10
class Stack:
def _init_(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"{item} pushed to stack")
def pop(self):
if not self.is_empty():
removed_item = self.stack.pop()
print(f"{removed_item} popped from stack")
return removed_item
else:
print("Stack is empty, cannot pop")
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty")
def is_empty(self):
return len(self.stack) == 0
def display(self):
if self.is_empty():
print("Stack is empty")
else:
print("Stack elements:", self.stack)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.display()
print("Top element is:", stack.peek())
stack.pop()
stack.display()
print("Top element is:", stack.peek())
PROGRAM11
def find_longest_line(filename):
try:
with open(filename, 'r') as file:
longest_line = ""
for line in file:
if len(line) > len(longest_line):
longest_line = line
return longest_line.strip()
except FileNotFoundError:
return "File not found. Please check the filename
and try again."
filename = input("Enter the filename: ")
longest_line = find_longest_line(filename)
print("The longest line in the file is:")
print(longest_line)
PROGRAM12
def remove_lines_with_a(input_filename,
output_filename):
try:
with open(input_filename, 'r') as infile,
open(output_filename, 'w') as outfile:
for line in infile:
if 'a' not in line.lower():
outfile.write(line)
print(f"Lines without 'a' have been written to
{output_filename}.")
except FileNotFoundError:
print("Input file not found. Please check the
filename and try again.")
input_file = input("Enter the input filename: ")
output_file = input("Enter the output filename: ")
remove_lines_with_a(input_file, output_file)
PROGRAM13
import pickle
def create_student_file(filename):
with open(filename, 'wb') as file:
num_students = int(input("Enter the number of
students: "))
for _ in range(num_students):
roll_number = int(input("Enter roll number: "))
name = input("Enter name: ")
student = {'roll_number': roll_number, 'name':
name}
pickle.dump(student, file)
print("Student file created successfully.")
def search_student_by_roll(filename, roll_number):
try:
with open(filename, 'rb') as file:
found = False
while True:
try:
student = pickle.load(file)
if student['roll_number'] == roll_number:
print(f"Student found: {student['name']}")
found = True
break
except EOFError:
break
if not found:
print("Roll number not found.")
except FileNotFoundError:
print("File not found. Please create the file first.")
filename = "students.dat"
create_student_file(filename)
search_roll = int(input("Enter roll number to search: "))
search_student_by_roll(filename, search_roll)
PROGRAM14
import csv
def search_student_by_name(filename, student_name):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
found = False
for row in reader:
if row and row[1].strip().lower() ==
student_name.strip().lower():
print("Student record found:", row)
found = True
break
if not found:
print("Student not found.")
except FileNotFoundError:
print("File not found. Please check the filename
and try again.")
filename = input("Enter the CSV filename (e.g.,
students.csv): ")
student_name = input("Enter the name of the student to
search: ")
search_student_by_name(filename, student_name)
PROGRAM15
import csv
def add_student(filename):
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
stream = input("Enter stream: ")
percentage = input("Enter percentage: ")
writer.writerow([roll_number, name, stream,
percentage])
print("Student record added successfully.")
def display_students(filename):
try:
reader = csv.reader(file)
print("\nStudent Records:")
print("Roll Number | Name | Stream |
Percentage")
print("---------------------------------------------------")
for row in reader:
print(f"{row[0]:<11} | {row[1]:<10} | {row[2]:<10}
| {row[3]}")
except FileNotFoundError:
print("File not found. Please add a student record
first.")
filename = "Student.csv"
while True:
print("\nMenu:")
print("1. Add a student record")
print("2. Display all student records")
print("3. Exit")
choice = input("Enter your choice (1, 2, or 3): ")
if choice == "1":
add_student(filename)
elif choice == "2":
display_students(filename)
elif choice == "3":
print("Exiting program.")
break
else:
print("Invalid choice. Please try again.")
PROGRAM16
PROGRAM18
Table : FITNESS
def delete_records():
try:
# Establish connection to the MySQL database
connection = mysql.connector.connect(
host='localhost', # Replace with your host
user='root', # Replace with your
username
password='yourpassword',# Replace with your
password
database='items' # Target database
)
if connection.is_connected():
cursor = connection.cursor()
# SQL query to delete records with name
"Stockable"
delete_query = "DELETE FROM category
WHERE name = 'Stockable';"
cursor.execute(delete_query)
connection.commit()
except Error as e:
print(f"Error: {e}")
finally:
# Close the database connection
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed.")
def fetch_all_records():
try:
# Establish connection to the MySQL database
connection = mysql.connector.connect(
host='localhost', # Replace with your host
user='root', # Replace with your
username
password='yourpassword',# Replace with your
password
database='menagerie' # Target database
)
if connection.is_connected():
cursor = connection.cursor()
# SQL query to fetch all records from the Pet
table
select_query = "SELECT * FROM Pet;"
cursor.execute(select_query)
except Error as e:
print(f"Error: {e}")
finally:
# Close the database connection
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed.")
# Call the function
fetch_all_records()