comp2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Identity

Name-Sayokh kabir mondal

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.

2.write a program in python to convert time from 12


hour to 24-hour format

3.Write a program in Python with a user defined


function with string as a parameter that replaces all
vowels in the string with a ""

4.Write a program in Python to print a "diamond


pattern" using a user defined function with *

5.Write a program in Python using a user defined


function to print Fibonacci series up to n terms.

6.Write a Python program to accept the username


"admin" as the default argument and password 123
entered by the user to allow lagin into the system

7.Write a program in python to calculate the value of


sine(x) using its Taylor series expansion up to n
terms with the help of a user defined function.
8.Write a "random number generator program in
Python that generates random numbers between 1
and 6 Which simulates dice.
9.write a menu-driven Python program using
different functions for the following menu: 1) check
number palindrome or not. 2) check mber is
Armstrong or not 3) Exit
10.wrote a Python program to implement a stack
using list data .structure.

11.write a program that accepts the filename of a


text file and displays longest line in the File. stack
using a list data

12.write a program in Python that removes all the


lines that contain the characters "a" in a file and
write it to another on file.
13.rite a program to create a binary file with roll
number and name Then search for a given roll
number and display the name, if the foll number is
not found, then display the appropriate message
14.Write a program to search the record of a
particular student from a sy file based on an
imputed name.
15.Write a program in python to perform a read and
write operation for a student.csv file having fields as
roll number, name, stream and percentage.

16 Write the SQL commands for the following based


on the given table CLUB.

17 Consider the following table named "SOFT


DRINK".

18.Consider the following table FITNESS with details


about fitness products being sold in the store.

19.Consider the following table named "GYM" with


details about fitness items being sold in the store.

20.Write the SQL commands from a) to d) for the


following based on the table STUDENT
21.a) Create a database named store in Create a
table msal. named customer with fields (c code int
cname char, c_city char) with c_code as primary key.
b) Insert four records into the
able customer. c) held "c_name" of the table
customer. order by

22.a) Create a database named school in mysql.


b) Create a table named student with fields(pd_code
int, bd_name char, pd_class int, st_mark int), with
pd_code as The primary key. c) Insert five records
into the table student
d) Display all records of the table student in the
descending order by field "pd_name"

23. Write a Python database connectivity script that


deletes records from a table named category of
database named items that have the name of the
data as Stockable".

24.Write a Python database connectivity script that


fetches all the records from the table named Pet of
database named menagerie.
PROGRAM1
def CelsiusToFahrenheit(temp):
farheit=((temp*(9/5))+32)
print("Entered temperature in fahrenheit: ",farheit)
celsius=float(input("Enter the temperature in degree
celsius: "))
CelsiusToFahrenheit(celsius)
PROGRAM2

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

CREATE TABLE club (


coach_id INTEGER PRIMARY KEY,
coachname TEXT NOT NULL,
age INTEGER,
sports char(20),
datofapp date,
pay INTEGER,
gender char(2)
);
-- insert some values
INSERT INTO club VALUES (1,
'Kukreja',35,'Karate',1996/03/27,1000, 'M');
INSERT INTO club VALUES (2,
'Ravina',34,'Karate',1998/01/20,1200, 'F');
INSERT INTO club Values
(3,'Karan',34,'Squash',1998/02/19,2000,'M');
INSERT INTO club Values
(4,'Tarun',33,'Basketball',1998/01/1,1500,'M');
INSERT INTO club Values
(5,'Zubin',36,'Swimming',1998/01/12,750,'M');
INSERT INTO club Values
(6,'Ketaki',33,'Swimming',1998/02/23,2000,'F');
INSERT INTO club Values
(7,'Aniket',34,'Squash',1998/02/19,200,'M');
INSERT INTO club Values
(8,'Zareen',34,'Squash',1998/02/19,2000,'F');
INSERT INTO club Values
(9,'Kush',34,'Karate',1998/02/19,2000,'M');
INSERT INTO club Values
(10,'Karan',34,'Basketball',1998/02/19,2000,'M');
-- fetch some values
SELECT sports , coachname from club
where sports='Swimming';
SELECT coachname , datofapp from club
order by datofapp desc;
Select coachname , pay , age , pay+0.15*pay from
club;
Select sports , count(coachname) from club
group by sports;
select * from club
order by Field(<column name>,<values sepcifying
order>);
Select * from club
order by field(sports,'Swimming','Karate');
PROGRAM17
CREATE TABLE SOFTDRINK
(DRINKCODE INTEGER,DNAME TEXT,PRICE
DECIMAL,CALORIES INTEGER);
INSERT INTO SOFTDRINK VALUES(101,"Lime and
Lemon",20.00,120);
INSERT INTO SOFTDRINK VALUES(102,"Apple
Drink",18.00,120);
INSERT INTO SOFTDRINK VALUES(103,"Nature
Nectar",15.00,115);
INSERT INTO SOFTDRINK VALUES(104,"Green
Mango",15.00,140);
INSERT INTO SOFTDRINK VALUES(105,"Aam
Panna",20.00,135);
INSERT INTO SOFTDRINK VALUES(106,"Mango Juice
Bahaar",12.00,150);
SELECT DNAME,DRINKCODE FROM SOFTDRINK
WHERE CALORIES>120;
SELECT DRINKCODE,DNAME,CALORIES FROM
SOFTDRINK ORDER BY CALORIES DESC;
SELECT DNAME,PRICE FROM SOFTDRINK WHERE
PRICE BETWEEN 12 AND 18;
UPDATE SOFTDRINK SET
PRICE=PRICE+0.10*PRICE;
SELECT*FROM SOFTDRINK;

PROGRAM18

Table : FITNESS

PCODE PNAME PRICE Manufacturer

P1 Treadmill 21000 Coscore

P2 Bike 20000 Aone

P3 Cross Trainer 14000 Reliable

P4 Multi Gym 34000 Coscore

P5 Massage Chair 5500 Regrosene

P6 Belly Vibrator Belt 6500 Ambawya


(i) To display the names of all the products with
price more than 20000.
(ii) To display the names of all products by the
manufacturer "Aone".
(iii) To change the price data of all the products by
applying 25% discount reduction.
(iv) To add a new row for product with the details :
SELECT PNAME FROM FITNESS WHERE PRICE >
20000;
SELECT PNAME FROM FITNESS WHERE
MANUFACTURER = "Aone";
UPDATE FITNESSSET PRICE = PRICE * 0.75;
PROGRAM19
CREATE TABLE GYM (
ICODE VARCHAR(255) PRIMARY KEY,
INAME VARCHAR(255),
PRICE INT,
BRANDNAME VARCHAR(255)
);
INSERT INTO GYM (ICODE, INAME, PRICE,
BRANDNAME) VALUES
('G101', 'Power Fit Exerciser', 20000, 'Power Gymea'),
('G102', 'Aquafit Hand Grip', 1800, 'Reliable'),
('G103', 'Cycle Bike', 14000, 'Ecobike'),
('6104', 'Protoner Extreme Gym', 30000, 'Coscore'),
('6105', 'Message Belt', 5000, 'Message Expert'),
('G106', 'Cross Trainer', 13000, 'GTC Fitness');
SELECT INAME
FROM GYM
WHERE INAME LIKE 'A%';
SELECT ICODE, INAME
FROM GYM
WHERE BRANDNAME = 'Reliable' OR BRANDNAME =
'Coscore';
UPDATE GYM
SET BRANDNAME = 'Fit Trend India'
WHERE ICODE = 'G101';
INSERT INTO GYM (ICODE, INAME, PRICE,
BRANDNAME) VALUES
('G107', 'Vibro exerciser', 21000, 'GTCFitness');
PROGRAM20
CREATE TABLE IF NOT EXISTS student (
student_id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
age INT,
marks INT
);
-- Insert data into the student table
INSERT INTO student (student_id, first_name,
last_name, age, marks)
VALUES
(1, 'John', 'Doe', 18, 85),
(2, 'Jane', 'Smith', 19, 92),
(3, 'Alice', 'Johnson', 20, 78),
(4, 'Bob', 'Williams', 18, 95);

-- Display the student table


SELECT * FROM student;

-- ALTER table to add a new attribute


ALTER TABLE student
ADD COLUMN email VARCHAR(100);

-- ALTER table to modify data type


ALTER TABLE student
MODIFY COLUMN age VARCHAR(3);

-- ALTER table to drop an attribute


ALTER TABLE student
DROP COLUMN marks;

-- UPDATE table to modify data


UPDATE student
SET age = 21
WHERE student_id = 3;

-- ORDER BY to display data in ascending order of age


SELECT * FROM student
ORDER BY age ASC;

-- ORDER BY to display data in descending order of


marks
SELECT * FROM student
ORDER BY marks DESC;

-- DELETE to remove a tuple


DELETE FROM student
WHERE student_id = 2;

-- GROUP BY and find the min, max, sum, count, and


average
SELECT
MIN(age) AS min_age,
MAX(age) AS max_age,
SUM(age) AS total_age,
COUNT(*) AS total_students,
AVG(age) AS avg_age
FROM student;
PROGRAM21
-- Create the database
CREATE DATABASE store;

-- Use the created database


USE store;

-- Create the customer table


CREATE TABLE customer (
c_code INT PRIMARY KEY,
c_name CHAR(50),
c_city CHAR(50)
);

-- Insert records into the customer table


INSERT INTO customer (c_code, c_name, c_city)
VALUES
(101, 'Alice', 'New York'),
(102, 'Bob', 'Los Angeles'),
(103, 'Charlie', 'Chicago'),
(104, 'Diana', 'Houston');

-- Display all customer records in ascending order by


c_name
SELECT * FROM customer
ORDER BY c_name ASC;
PROGRAM22
-- a) Create the database named school
CREATE DATABASE school;

-- Use the created database


USE school;

-- b) Create the student table


CREATE TABLE student (
pd_code INT PRIMARY KEY,
pd_name CHAR(50),
pd_class INT,
st_mark INT
);
-- c) Insert five records into the student table
INSERT INTO student (pd_code, pd_name, pd_class,
st_mark) VALUES
(1, 'Alice', 10, 85),
(2, 'Bob', 9, 78),
(3, 'Charlie', 10, 92),
(4, 'Diana', 8, 88),
(5, 'Ethan', 9, 81);

-- d) Display all records of the student table in


descending order by pd_name
SELECT * FROM student
ORDER BY pd_name DESC;
PROGRAM23
import mysql.connector
from mysql.connector import Error

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()

print(f"Deleted {cursor.rowcount} record(s) from


the category table.")

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


delete_records()
import mysql.connector
PROGRAM15
PROGRAM24

from mysql.connector import Error

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)

# Fetch all records and display them


records = cursor.fetchall()
print("Records from the Pet table:")
for record in records:
print(record)

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()

You might also like