Kirti Cs Practical File-2
Kirti Cs Practical File-2
def calculator():
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice == 1:
print(f"Result: {num1 + num2}")
elif choice == 2:
print(f"Result: {num1 - num2}")
elif choice == 3:
print(f"Result: {num1 * num2}")
elif choice == 4:
if num2 != 0:
print(f"Result: {num1 / num2}")
else:
print("Error! Division by zero.")
else:
print("Invalid choice.")
calculator()
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
else:
print("Fibonacci sequence:")
for i in range(terms):
print(fibonacci(i), end=" ")
import csv
FILE_NAME = "students.csv"
def add_student():
with open(FILE_NAME, mode="a", newline="") as file:
writer = csv.writer(file)
student_id = input("Enter Student ID: ")
name = input("Enter Name: ")
marks = input("Enter Marks: ")
writer.writerow([student_id, name, marks])
print("Student added successfully!")
def display_students():
try:
with open(FILE_NAME, mode="r") as file:
reader = csv.reader(file)
print("\nStudent Records:")
print("{:<10} {:<20} {:<10}".format("Student ID",
"Name", "Marks"))
print("-" * 40)
for row in reader:
print("{:<10} {:<20} {:<10}".format(row[0],
row[1], row[2]))
except FileNotFoundError:
print("No records found. The file doesn't exist yet.")
def update_marks():
student_id = input("Enter Student ID to update: ")
updated = False
records = []
try:
with open(FILE_NAME, mode="r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == student_id:
print(f"Current Marks: {row[2]}")
row[2] = input("Enter New Marks: ")
updated = True
records.append(row)
if updated:
with open(FILE_NAME, mode="w", newline="") as
file:
writer = csv.writer(file)
writer.writerows(records)
print("Marks updated successfully!")
else:
print("Student ID not found.")
except FileNotFoundError:
def menu():
while True:
print("\nStudent Management System")
print("1. Add Student")
print("2. Display Students")
print("3. Update Marks")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
add_student()
elif choice == "2":
display_students()
elif choice == "3":
update_marks()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
Q4: Python implementation of the Bubble Sort algorithm
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already sorted, no need to
compare them
for j in range(0, n - i - 1):
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater than the
next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
if _name_ == "_main_":
data = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted array:", data)
sorted_data = bubble_sort(data)
print("Sorted array:", sorted_data)
def is_empty(self):
return len(self.stack) == 0
def peek(self):
if self.is_empty():
return "Stack is empty"
return self.stack[-1]
def size(self):
return len(self.stack)
def display(self):
if self.is_empty():
return "Stack is empty"
return self.stack
def create_connection():
try:
conn = mysql.connector.connect(
host='localhost',
user='root',
password='password',
database='your_database_name' )
if conn.is_connected():
return conn
except mysql.connector.Error as err:
print(f"Error: {err}")
return None
def create_table(cursor):
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT
)
cursor.execute(create_table_query)
def main():
conn = create_connection()
if conn is None:
return
cursor = conn.cursor()
create_table(cursor)
conn.commit()
conn.close()
main()
Q7 Create a binary file with the name and roll number. Search
for a given roll number and display the name, if not found
display appropriate message.
import pickle
def create_binary_file(filename):
students = { 101: 'Alice',
102: 'Bob',
103: 'Charlie',
104: 'David' }
if roll_number in students:
print(f"Name: {students[roll_number]}")
else:
print("Roll number not found.")
except FileNotFoundError:
print("Binary file not found.")
create_binary_file('students.dat')
def main():
arr = [int(x) for x in input("Enter a list of numbers
separated by spaces: ").split()]
arr.sort() # Sort the array for binary search
if choice == 1:
result = linear_search(arr, target)
if result != -1:
print(f"Linear Search: Element found at index
{result}")
else:
print("Linear Search: Element not found")
elif choice == 2:
result = binary_search(arr, target)
if result != -1:
print(f"Binary Search: Element found at index
{result}")
else:
print("Binary Search: Element not found")
else:
print("Invalid choice")
if _name_ == "_main_":
main()
students = {}
n = int(input("Enter the number of students: "))
for _ in range(n):
admission_no = input("Enter admission number: ")
roll_no = input("Enter roll number: ")
name = input("Enter name: ")
percentage = float(input("Enter percentage: "))
students[admission_no] = {
'Roll Number': roll_no,
'Name': name,
'Percentage': percentage }
Q10 : Read a text file line by line and display each word
separated by a #.
def display_words(filename):
with open(filename, 'r') as file:
for line in file:
words = line.split() # Split the line into words
for word in words:
print(word) # Display each word on a new line
filename = input("Enter the filename: ")
display_words(filename)
Q11 : Write a Python code to find the size of the file in
bytes, the number of lines, number of words and no. of
character.
import os
def file_statistics(filename):
try:
with open(filename, 'r') as file:
lines = file.readlines()
num_lines = len(lines)
num_words = 0
num_chars = 0
file_size = os.path.getsize(filename)
print(f"File Size: {file_size} bytes")
print(f"Number of Lines: {num_lines}")
print(f"Number of Words: {num_words}")
print(f"Number of Characters: {num_chars}")
except FileNotFoundError:
print("The specified file does not exist.")
filename = input("Enter the filename: ")
file_statistics(filename)
Answer
(a)
| POW(2, 3) |
| 8 |
(b)
| ROUND(342.9234, -1)
| 340 |
(c)
| LENGTH("Informatics
Practices") |
| 21 |
(d)
| YEAR("1979/11/26") | MONTH("1979/11/26") | DAY("1979/11/26") |
MONTHNAME("1979/11/26") |
| 1979 | 11 | 26 | November |
(e)
| LEFT("INDIA", 3) | RIGHT("ComputerScience", 4) |
MID("Informatics", 3, 4) | SUBSTR("Practices", 3) |
+-------+----------------+--------+
| P02 | TOOTHPASTE | 54 |
| P04 | TOOTHPASTE | 65 |
| P03 | SOAP | 25 |
| P05 | SOAP | 38 |
+-------+----------------+--------+--------------
+----------+
(a) Display the MatchID of all those matches where both the
teams have scored more than 70.
(b) Display the MatchID of all those matches where
FirstTeam has scored less than 70 but SecondTeam has
scored more than 70.
(c) Display the MatchID and date of matches played by
Team 1 and won by it.
(d) Display the MatchID of matches played by Team 2 and
not won by it.
(e) Change the name of the relation TEAM to T_DATA. Also
change the attributes TeamID and TeamName to T_ID and
T_NAME respectively.
(a)
SELECT MatchID
FROM MATCH_DETAILS
WHERE FirstTeamScore > 70 AND
SecondTeamScore > 70;
Output
| MatchID |
| M1 |
(b)
SELECT MatchID
FROM MATCH_DETAILS
WHERE FirstTeamScore < 70 AND
SecondTeamScore > 70;
Output
| MatchID |
| M5 |
(c)
SELECT MatchID, MatchDate
FROM MATCH_DETAILS
WHERE FirstTeamID = 1 AND FirstTeamScore >
SecondTeamScore;
Output
| MatchID | MatchDate |
| M1 | 2018-07-17 |
| M3 | 2018-07-19 |
(d)
SELECT MatchID
FROM MATCH_DETAILS
WHERE SecondTeamID = 2 AND SecondTeamScore <=
FirstTeamScore;
Output
| MatchID |
| M1 |
(e)
ALTER TABLE TEAM RENAME TO T_DATA;
ALTER TABLE T_DATA CHANGE COLUMN TeamID T_ID int;
ALTER TABLE T_DATA CHANGE COLUMN TeamName T_NAME
CHAR(20);
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")
cursor = connection.cursor()
cursor.execute('''
UPDATE users
SET age = 35
WHERE name = 'Alice'''')
print("Record updated successfully!")
connection.commit()
connection.close()
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")
cursor = connection.cursor()
cursor.execute('''
DELETE FROM users
WHERE name = 'Alice'''')
print("Record deleted successfully!")
connection.commit()
connection.close()
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")
cursor = connection.cursor()
connection.close()
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")
cursor = connection.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL)''')
connection.commit()
connection.close()
import mysql.connector
def fetch_users_by_age(min_age):
connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")
cursor = connection.cursor()
cursor.execute('SELECT * FROM users WHERE age > ?',
(min_age,))
rows = cursor.fetchall()
connection.close()
return rows
users = fetch_users_by_age(25)
print("Users older than 25:")
for user in users:
print(user)