Project
Project
EX. NO: 1
AIM: To write a menu driven Python Program to perform Arithmetic operations (+,-*, /) Based on
the user’s choice.
CODE:
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
if choice == '1':
print(f"Result: {add(num1, num2)}")
elif choice == '2':
print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
else:
print("Invalid input")
2
OUTPUT:
3
EX.NO: 2
CODE:
def fibonacci(n):
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
OUTPUT
4
5
EX.NO: 3
AIM: To write a menu driven Python Program to find Factorial and sum of list of
numbers Using function.
CODE :
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def sum_of_list(numbers):
return sum(numbers)
print("Select operation:")
print("1. Factorial")
print("2. Sum of List")
if choice == '1':
num = int(input("Enter a number: "))
print(f"Factorial: {factorial(num)}")
elif choice == '2':
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
print(f"Sum: {sum_of_list(numbers)}")
else:
print("Invalid input")
OUTPUT:
6
7
EX.NO: 4
CODE:
import math
def math_functions():
print("1. Find Square of a number")
print("2. Find Log10 of a number")
print("3. Find Quad (number^4) of a number")
choice = int(input("Enter your choice: "))
num = float(input("Enter a number: "))
if choice == 1:
print(f"Square of {num} is {num ** 2}")
elif choice == 2:
if num > 0:
print(f"Log10 of {num} is {math.log10(num)}")
else:
print("Log10 is not defined for non-positive numbers.")
elif choice == 3:
print(f"Quad of {num} is {num ** 4}")
else:
print("Invalid choice.")
math_functions()
OUTPUT:
8
9
EX.NO: 5
CODE:
import random
def roll_dice():
print(f"The dice rolled: {random.randint(1, 6)}")
roll_dice()
OUTPUT:
10
11
EX.NO: 6
AIM: To write a Python Program to Read a text file “Story.txt” line by line and display
Each word separated by ‘#’.
CODE:
def read_and_display():
with open("Story.txt", "r") as file:
for line in file:
print("#".join(line.split()))
read_and_display()
Content of Story.txt:
OUTPUT:
12
13
EX.NO: 7
AIM: To write a Python Program to read a text file “Story.txt” and displays the
number of Vowels/ Consonants/ Lowercase / Uppercase/characters in the file.
CODE:
def count_characters():
vowels = "aeiouAEIOU"
with open("Story.txt", "r") as file:
text = file.read()
vowel_count = sum(1 for char in text if char in vowels)
consonant_count = sum(1 for char in text if char.isalpha() and char not in vowels)
uppercase_count = sum(1 for char in text if char.isupper())
lowercase_count = sum(1 for char in text if char.islower())
character_count = len(text)
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
print(f"Uppercase: {uppercase_count}")
print(f"Lowercase: {lowercase_count}")
print(f"Total Characters: {character_count}")
count_characters()
OUTPUT:
14
15
EX.NO:8
AIM: To write a python program to read lines from a text file “Sample.txt” and copy
those lines Into another file which are starting with an alphabet ‘a’ or ‘A’.
CODE:
def copy_lines():
with open("Sample.txt", "r") as source, open("New.txt", "w") as target:
for line in source:
if line.startswith(('A', 'a')):
target.write(line)
copy_lines()
EX.NO: 9
AIM: To write a Python Program to Create a binary file with roll number and name.
Search for a given roll number and display the name, if not found display
Appropriate message.
CODE:
import pickle
def create_binary_file():
with open("records.dat", "wb") as file:
n = int(input("Enter the number of records: "))
for _ in range(n):
roll = int(input("Enter Roll number: "))
name = input("Enter Name: ")
pickle.dump({'roll': roll, 'name': name}, file)
def search_binary_file():
roll_to_search = int(input("Enter Roll number to search: "))
found = False
with open("records.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record['roll'] == roll_to_search:
print(f"Name: {record['name']}")
found = True
break
except EOFError:
if not found:
print("Record not found.")
create_binary_file()
search_binary_file()
OUTPUT:
18
19
EX.NO: 10
AIM: To write a Python Program to Create a binary file with roll number, name, mark
And update/modify the mark for a given roll number.
CODE:
import pickle
def create_binary_file():
with open("records.dat", "wb") as file:
n = int(input("Enter the number of records: "))
for _ in range(n):
roll = int(input("Enter Roll number: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
pickle.dump({'roll': roll, 'name': name, 'marks': marks}, file)
def update_binary_file():
roll_to_update = int(input("Enter Roll number to update marks: "))
updated = False
records = []
with open("records.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record['roll'] == roll_to_update:
record['marks'] = int(input("Enter new marks: "))
updated = True
records.append(record)
except EOFError:
pass
if updated:
print("Record updated successfully.")
else:
20
INPUT :
OUTPUT:
21
EX.NO: 11
AIM: To write a Python program Create a CSV file to store Empno, Name, Salary and
Search any Empno and display Name, Salary and if not found display appropriate
Message.
CODE:
import csv
def create_csv():
with open("employees.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["EmpNo", "Name", "Salary"])
n = int(input("Enter the number of employees: "))
for _ in range(n):
empno = input("Enter Employee number: ")
name = input("Enter Name: ")
salary = input("Enter Salary: ")
writer.writerow([empno, name, salary])
def search_csv():
empno_to_search = input("Enter Employee number to search: ")
found = False
with open("employees.csv", "r") as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
if row[0] == empno_to_search:
print(f"Name: {row[1]}, Salary: {row[2]}")
found = True
break
if not found:
print("Record not found.")
INPUT:
OUTPUT:
23
EX.NO: 12
CODE
:
def stack_operations():
stack = []
while True:
print("\n1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
element = input("Enter element to push: ")
stack.append(element)
print(f"{element} pushed into the stack.")
elif choice == 2:
if stack:
print(f"Popped element: {stack.pop()}")
else:
print("Stack is empty.")
elif choice == 3:
print(f"Stack: {stack}")
elif choice == 4:
print("Exiting...")
break
else:
print("Invalid choice.")
stack_operations()
24
OUTPUT:
25
EX.NO: 13
AIM: To write a Python Program to integrate mysql with Python by inserting records
to Emp table and display the records.
CODE:
import mysql.connector
def mysql_insert_and_display():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
cursor = conn.cursor()
cursor.execute("INSERT INTO emp (EmpID, Name, Salary) VALUES (101, 'Rahul', 50000)")
cursor.execute("INSERT INTO emp (EmpID, Name, Salary) VALUES (102, 'Anjali', 60000)")
conn.commit()
# Display records
cursor.execute("SELECT * FROM emp")
for row in cursor.fetchall():
print(row)
conn.close()
mysql_insert_and_display()
OUTPUT:
26
27
EX.NO: 14
CODE:
import mysql.connector
def mysql_search_record():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
cursor = conn.cursor()
if result:
print(f"EmpID: {result[0]}, Name: {result[1]}, Salary: {result[2]}")
else:
print("Record not found.")
conn.close()
mysql_search_record()
OUTPUT:
.
28
29
EX.NO: 15
CODE:
import mysql.connector
def mysql_update_record():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="school"
)
cursor = conn.cursor()
if cursor.rowcount > 0:
print("Record updated successfully.")
else:
print("Record not found.")
conn.close()
mysql_update_record()
OUTPUT:
30
31
Ex.No: 16
AIM: To write Queries for the following Questions based on the given table:
OITPUT:
32
(e) Write a Query to List all the tables that exists in the current database.
Query: SHOW TABLES;
OUTPUT:
(f) Write a Query to insert all the rows of above table into Info table.
Query: INSERT INTO STU VALUES
(1, ‘Suman’, ‘F’, 22, ‘Computer’, ‘1997-01-10’, 500),
(2, ‘Amanir’, ‘M’, 23, ‘Mechanical’, ‘1998-03-24’, 350),
(3, ‘Priyanka’, ‘F’, 21, ‘Electrical’, ‘1996-12-12’, 800),
(4, ‘Karak’, ‘M’, 24, ‘Computer’, ‘1999-07-01’, 720),
(5, ‘Mena’, ‘F’, 20, ‘Civil’, ‘1997-09-05’, 280),
(6, ‘Adi’, ‘M’, 22, ‘Electrical’, ‘1997-06-27’, 370),
(7, ‘Shorya’, ‘F’, 23, ‘Mechanical’, ‘1997-02-25’, 280),
(8, ‘Vish’, ‘M’, 25, ‘Civil’, ‘1997-07-31’, 250);
OUTPUT:
(h)Write a Query to display all the details of the Employees from the above table
‘STU’.
Query: SELECT * FROM Students;
OUTPUT:
33
34
35
Ex.No: 17
AIM: To write Queries for the following Questions based on the given table:
OUTPUT:
OUTPUT:
36
OUTPUT:
(d) Write a Query to list name of the students whose ages are between 20 to 23.
Query: SELECT Name FROM STU WHERE Age BETWEEN 20 AND 23;
OUTPUT:
(e) Write a Query to display the name of the students whose name is starting with
‘A’.
Query: SELECT Name FROM STU WHERE Name LIKE ‘A%’;
OUTPUT:
(f) Write a query to list the names of those students whose name have second
alphabet ‘n’ in their Names.
Query SELECT Name FROM STU WHERE Name LIKE ‘_N%’;
OUTPUT:
37
38
39
Ex.No: 18
AIM: To write Queries for the following Questions based on the given table:
OUTPUT:
(b)Write a Query to change the fess of Student to 170 whose Roll number is 1,
if the existing fess Is less than 130.
Query: UPDATE STU SET Fees = 350 WHERE Rollno = 1 AND Fees < 310;
OUTPUT:
40
(c) Write a Query to add a new column Area of type varchar in table STU.
Query: ALTER TABLE STU ADD Area VARCHAR(20);
OUTPUT:
(d)Write a Query to Display Name of all students whose Area Contains NULL.
Query: SELECT NAME FROM STU WHERE AREA IS NULL;
OUTPUT:
OUTPUT:
Ex.No: 19.
AIM: To write Queries for the following Questions based on the given table:
TABLE: STOCK
P no P name D code Qty Unit Price Stock date
TABLE: DEALERS
D code D name
(a)To display the total Unit price of all the products whose Dcode as 102.
Query: SELECT SUM(UnitPrice) AS TotalPrice FROM Stock WHERE Dcode = 201;
OUTPUT:
(b)To display details of all products in the stock table in descending order of
Stock date.
Query: SELECT * FROM Stock ORDER BY StockDate DESC;
OUTPUT:
44
(c) To display maximum unit price of products for each dealer individually as per
dcode From the table Stock.
Query: SELECT Dcode, MAX(UnitPrice) AS MaxPrice FROM Stock GROUP BY Dcode;
OUTPUT:
(d)To display the Pname and Dname from table stock and dealers.
Query: SELECT S.Pname, D.Dname FROM Stock S JOIN Dealers D ON S.Dcode =
D.Dcode;
OUTPUT: