0% found this document useful (0 votes)
13 views

CS Practical File - Adarsh (1)

Computer science practical file using python and MySQL.

Uploaded by

mp8482936
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

CS Practical File - Adarsh (1)

Computer science practical file using python and MySQL.

Uploaded by

mp8482936
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

1

EX. NO: 1

AIM: To write a menu driven Python Program to perform Arithmetic operations (+,-*,
/) Based on the user’s choice.

CODE:

def add(x, y):

return x + y

def subtract(x, y):

return x – y

def multiply(x, y):

return x * y

def divide(x, y):

return x / y

print(“Select operation:”)

print(“1. Add”)

print(“2. Subtract”)

print(“3. Multiply”)

print(“4. Divide”)

choice = input(“Enter choice (1/2/3/4): “)

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

If choice == ‘1’:
2

print(“Result:”, add(num1, num2))

elif choice == ‘2’:

print(“Result:”, subtract(num1, num2))

elif choice == ‘3’:

print(“Result:”, multiply(num1, num2))

elif choice == ‘4’:

print(“Result:”, divide(num1, num2))

else:

print(“Invalid input”)

OUTPUT:
3

EX.NO: 2

AIM: To write a Python Program to display Fibonacci Series up to ‘n’ numbers.

CODE:

def fibonacci(n):

a, b = 0, 1

for _ in range(n):

print(a, end=' ')

a, b = b, a + b

n = int(input("Enter the number of terms: "))

fibonacci(n)

OUTPUT:
4

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

choice = input(“Enter choice (1/2): “)

If choice == ‘1’:

num = int(input(“Enter a number: “))

print(“Factorial:”, factorial(num))

elif choice == ‘2’:

numbers = list(map(int, input(“Enter numbers separated by space: “).split()))

print(“Sum:”, sum_of_list(numbers))
5

else:

print(“Invalid input”)

OUTPUT:
6

EX.NO: 4

AIM: To write a Python program to implement python mathematical functions to


find:

(i) To find Square of a number.


(ii) To find Log of a number(i.e. Log10)
(iii) To find Quad of a number

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:
7

EX.NO: 5

AIM: To write a Python program to generate random number between 1 to 6 to


simulate The dice.

CODE:

Import random

def roll_dice():
print(f”The dice rolled: {random.randint(1, 6)}”)

Roll_dice()

OUTPUT:
8

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

STORY:
If “stary.txt” contains: “Learning Python is Fun”

OUTPUT:
9

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

print(f”Vowels: {vowel_count}”)
print(f”Consonants: {consonant_count}”)
print(f”Uppercase: {uppercase_count}”)
print(f”Lowercase: {lowercase_count}”)
Count_characters()

STORY:
If “story.txt” contains: “Python Programming”

OUTPUT:
10

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

INPUT FILE: Sample.txt

OUTPUT FILE: New.txt


11

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:
12

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

With open(“records.dat”, “wb”) as file:


For record in records:
Pickle.dump(record, file)
13

If updated:
print(“Record updated successfully.”)
else:
print(“Record not found.”)

Create_binary_file()
Update_binary_file()

OUTPUT:
14

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.”)

Create_csv()
Search_csv()
15

OUTPUT:
16

EX.NO: 12

AIM: To write a Python program to implement Stack using a list data-structure.

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)
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:
Break
else:
print(“Invalid choice.”)
Stack_operations()

OUTPUT:
17

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

# Create table if it doesn’t exist


Cursor.execute(“CREATE TABLE IF NOT EXISTS emp (EmpID INT, Name
VARCHAR(50), Salary INT)”)

# Insert records
Cursor.execute(“INSERT INTO emp (EmpID, Name, Salary) VALUES (201, ‘Rahul’,
50000)”)
Cursor.execute(“INSERT INTO emp (EmpID, Name, Salary) VALUES (202, ‘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:
18

EX.NO: 14

AIM: To write a Python Program to integrate mysql with Python to search an


Employee
Using EMPID and display the record if present in already existing table EMP, if not
Display the appropriate message.

CODE:

Import mysql.connector
def mysql_search_record():
Conn = mysql.connector.connect(host=”localhost”, user=”root”,
password=”password”, database=”school”)
Cursor = conn.cursor()

Emp_id = int(input(“Enter Employee ID to search: “))


Cursor.execute(“SELECT * FROM emp WHERE EmpID = %s”, (emp_id,))
Result = cursor.fetchone()

If result:
print(f”EmpID: {result[0]}, Name: {result[1]}, Salary: {result[2]}”)
else:
print(“Record not found.”)
Conn.close()
mysql_search_record()

OUTPUT:
19

EX.NO: 15

AIM: To write a Python Program to integrate mysql with Python to search an


Employee using EMPID and update the Salary of an employee if present in already
existing table EMP, if not display the appropriate message.

CODE:

Import mysql.connector

def mysql_update_record():
Conn = mysql.connector.connect(host=”localhost”, user=”root”,
password=”password”, database=”school”)
Cursor = conn.cursor()

Emp_id = int(input(“Enter Employee ID to update salary: “))


New_salary = int(input(“Enter new salary: “))
Cursor.execute(“UPDATE emp SET Salary = %s WHERE EmpID = %s”, (new_salary,
emp_id))
Conn.commit()

If cursor.rowcount > 0:
print(“Record updated successfully.”)
else:
print(“Record not found.”)

Conn.close()
mysql_update_record()

OUTPUT:
20

Ex.No: 16

AIM: To write Queries for the following Questions based on the given table:

Roll no. Name Gender Age Dept DOB Fees

1 Riya F 22 Computer 1997-01-10 300

2 Aman M 23 Mechanical 1998-03-24 400

3 Priya F 21 Electrical 1996-12-12 350

4 Karan M 24 Computer 1999-07-01 500

5 Meera F 20 Civil 1997-09-05 450

6 Aditya M 22 Electrical 1997-06-27 320

7 Sneha F 23 Mechanical 1997-02-25 370

8 Vikash M 25 Civil 1997-07-31 420

(a) Write a Query to Create a new database in the name of “STUDENTS”


Query: CREATE DATABASE STUDENTS;

(b) Write a Query to Open the database “STUDENTS”


Query: USE STUDENTS;

(c) Write a Query to create the above table called: Info


Query: CREATE TABLE STU(Rollno int Primary key,Name varchar(10),Gender
varchar(3),
Age int,Dept varchar(15),DOA date,Fees int);

(d) Write a Query to list all the existing database names.


Query: SHOW DATABASES;
21

OUTPUT:

(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: SELECT Rollno, Name, Dept FROM Students;

OUTPUT:
22

(g) Write a Query to insert all the rows of above table into Info table.
Query:
INSERT INTO STU VALUES (101,’Riya’,’F’, 22 ,’COMPUTER’, 2021-05-10, 300)
INSERT INTO STU VALUES (102 ,’Aman’,’M’,23 ,’Mechanical’,2020-08-15 ,400)
INSERT INTO STU VALUES (103,’Priya’,’F’,21,’Electrical’,2022-01-20,350)
INSERT INTO STU VALUES (104,’Karan’,”M’, 24,’COMPUTER’,2021-03-12,500)
INSERT INTO STU VALUES (105 ,’Meera’,’F’,20,’CIVIL’,2022-07-01,450)
INSERT INTO STU VALUES (106,’Aditya’,’M’,22,’ELECTRICAL’,2021-11-30, 320)
INSERT INTO STU VALUES(107,’Sneha’,’F’,23,’MECHANICAL’,020-09-05,370);

(h) Write a Query to display all the details of the Employees from the above table
‘STU’.
Query: SELECT * FROM Students;

OUTPUT:
23

Ex.No: 17

AIM: To write Queries for the following Questions based on the given table:

Roll no. Name Gender Age Dept DOB Fees

1 Riya F 22 Computer 1997-01- 300


10

2 Aman M 23 Mechanical 1998-03- 400


24

3 Priya F 21 Electrical 1996-12- 350


12

4 Karan M 24 Computer 1999-07- 500


01

5 Meera F 20 Civil 1997-09- 450


05

6 Aditya M 22 Electrical 1997-06- 320


27

7 Sneha F 23 Mechanical 1997-02- 370


25

8 Vikash M 25 Civil 1997-07- 420


31

(a) Write a Query to select distinct Department from STU table.


Query: SELECT DISTICT(DEPT ) FROM STU;

OUTPUT:
24

(b) To show all information about students of Mechanical ldepartment.


Query: SELECT * FROM STU WHERE Dept = ‘Mechanical’;

OUTPUT:

(c) Write a Query to list name of female students in Electrical Department


Query: SELECT Name FROM STU WHERE Dept = ‘Electrical’ AND Gender = ‘F’;

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:
25

(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:
26

Ex.No: 18

AIM: To write Queries for the following Questions based on the given table:

Roll no. Name Gender Age Dept DOB Fees

1 Riya F 22 Computer 1997-01-10 300

2 Aman M 23 Mechanical 1998-03-24 400

3 Priya F 21 Electrical 1996-12-12 350

4 Karan M 24 Computer 1999-07-01 500

5 Meera F 20 Civil 1997-09-05 450

6 Aditya M 22 Electrical 1997-06-27 320

7 Sneha F 23 Mechanical 1997-02-25 370

8 Vikash M 25 Civil 1997-07-31 420

(a) Write a Query to delete the details of Roll number is 8.


Query: DELETE FROM STU WHERE Rollno = 8;

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;
27

OUTPUT:

(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;
28

OUTPUT:

(e) Write a Query to delete Area Column from the table STU.
Query: ALTER TABLE STU DROP AREA;

OUTPUT:

(f) Write a Query to delete table from Database.


Query: DROP TABLE STU;
29

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
201 Ball pen 201 120 15 2022-06-01
202 Gel pen 202 80 25 2022-05-15
203 Highlighter 201 50 30 2022-04-20
204 Permanent marker 202 60 20 2022-07-10

TABLE: DEALERS
D code D name
Stationary
201
Express
202 Office Mart

(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:
30

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

You might also like