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

Kirti Cs Practical File-2

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

Kirti Cs Practical File-2

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

Q1 : Write a Python program to implement a calculator with

basic operations (+, -, *, /).

def calculator():
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = int(input("Enter your choice (1-4): "))


if choice in [1, 2, 3, 4]:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

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

Q2: Generate a Fibonacci sequence up to n terms using


recursion.

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)

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


if terms <= 0:
print("Please enter a positive number.")

else:
print("Fibonacci sequence:")
for i in range(terms):
print(fibonacci(i), end=" ")

Q3 : Write a Python program to manage student records


using a CSV file. The program should allow adding new
student data, displaying all records, and updating a
student.

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:

print("No records found. The file doesn't exist yet.")

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)

Q5 Python implementation of a stack.


class Stack:
def _init_(self):
self.stack = []

def is_empty(self):

return len(self.stack) == 0

def push(self, item):


self.stack.append(item)
def pop(self):
if self.is_empty():
return "Stack is empty"
return self.stack.pop()

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

Q6: To write a Python Program to integrate MYSQL with


Python by Inserting Data into a Table
import mysql.connector

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 insert_data(cursor, name, age):


insert_query = "INSERT INTO users (name, age) VALUES
(%s, %s)"
cursor.execute(insert_query, (name, age))

def main():
conn = create_connection()
if conn is None:
return

cursor = conn.cursor()
create_table(cursor)

name = "John Doe"


age = 30
insert_data(cursor, name, age)

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' }

with open(filename, 'wb') as file:


pickle.dump(students, file)

def search_roll_number(filename, roll_number):


try:
with open(filename, 'rb') as file:
students = pickle.load(file)

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

roll_number_to_search = int(input("Enter the roll number to


search: "))
search_roll_number('students.dat', roll_number_to_search)

Q8: Write a python program to implement searching methods


based on user choice using a list data-structure.

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i
return -1

def binary_search(arr, target):


low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

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

print("Choose a searching method:")


print("1. Linear Search")
print("2. Binary Search")
choice = int(input("Enter your choice (1 or 2): "))

target = int(input("Enter the number to 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()

Q9: WAP to store students’ details like admission number,


roll number, name and percentage in a dictionary and
display information on the basis of admission number.

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 }

admission_no = input("Enter admission number to search:


")
if admission_no in students:
print(f"Details for Admission Number {admission_no}:")
for key, value in students[admission_no].items():
print(f"{key}: {value}")
else:
print("Admission number not found.")

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

for line in lines:


num_words += len(line.split())
num_chars += len(line)

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)

Q12: Consider the following tables SCHOOL and ADMIN and


answer this question :
Give the output the following SQL queries :
Select Designation Count (*) From Admin Group By
Designation Having Count (*) <2;
SELECT max (EXPERIENCE) FROM SCHOOL;
SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE >12
ORDER BY TEACHER;
SELECT COUNT (*), GENDER FROM ADMIN GROUP BY
GENDER;
Q13: Write the output SELECT POW(2, 3);
(b) SELECT ROUND(342.9234, -1);
(c) SELECT LENGTH("Informatics Practices");
(d) SELECT YEAR("1979/11/26"), MONTH("1979/11/26"),
DAY("1979/11/26"), MONTHNAME("1979/11/26");
(e) SELECT LEFT("INDIA", 3), RIGHT("ComputerScience", 4),
MID("Informatics", 3, 4), SUBSTR("Practices", 3);
produced by the following SQL statements:

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

| IND | ence | form


| actices |

Q14: Consider the following table named "Product", showing


details of products being sold in a grocery shop.

PCode PName UPrice Manufacturer

P01 Washing Powder 120 Surf

P02 Toothpaste 54 Colgate

P03 Soap 25 Lux

P04 Toothpaste 65 Pepsodent


PCode PName UPrice Manufacturer

P05 Soap 38 Dove

P06 Shampoo 245 Dove

Write SQL queries for the following:


(a) Create the table Product with appropriate data types
and constraints.
(b) Identify the primary key in Product.
(c) List the Product Code, Product name and price in
descending order of their product name. If PName is the
same, then display the data in ascending order of price.
(d) Add a new column Discount to the table Product.
(e) Calculate the value of the discount in the table Product
as 10 per cent of the UPrice for all those products where
the UPrice is more than 100, otherwise the discount will be
0.

CREATE TABLE Product (


PCode VARCHAR(10) PRIMARY KEY,
PName VARCHAR(50),
UPrice int,
Manufacturer VARCHAR(50));

(b) The primary key in the table "Product" is PCode.

(c)SELECT PCode, PName, UPrice


FROM Product
ORDER BY PName DESC, UPrice ASC;
Output
+-------+----------------+--------+

| PCode | PName | UPrice |

+-------+----------------+--------+

| P01 | WASHING POWDER | 120 |

| P02 | TOOTHPASTE | 54 |

| P04 | TOOTHPASTE | 65 |

| P03 | SOAP | 25 |

| P05 | SOAP | 38 |

| P06 | SHAMPOO | 245 |

(d) ALTER TABLE Product


ADD COLUMN Discount float;
(e) UPDATE Product
SET Discount = IF(UPrice > 100, (UPrice * (10/100)) +
UPrice, 0);
Output
SELECT * FROM Product;

| PCode | PName | UPrice | Manufacturer | Discount


|

+-------+----------------+--------+--------------
+----------+

| P01 | WASHING POWDER | 120 | SURF | 12


|

| P02 | TOOTHPASTE | 54 | COLGATE | 0


|

| P03 | SOAP | 25 | LUX | 0


|

| P04 | TOOTHPASTE | 65 | PEPSODENT | 0


|
| P05 | SOAP | 38 | DOVE | 0
|

| P06 | SHAMPOO | 245 | DOVE | 24.5


|

Q15:Using the sports database containing two relations


(TEAM, MATCH_DETAILS) and write the queries for the
following:

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

Q16: Write a Python program to connect to a MySQL


database and update the age of the user named 'Alice' in
the users table to 35. Ensure the changes are committed,
and the database connection is closed properly after the
operation.

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

Q17: Write a Python program to connect to a MySQL


database and delete the record of the user named 'Alice'
from the users table.

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

Q18: Write a Python program to connect to a MySQL


database and retrieve all records from the users table.

import mysql.connector

connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database")

cursor = connection.cursor()

cursor.execute('SELECT * FROM users')


rows = cursor.fetchall()

print("Data from users table:")


for row in rows:
print(row)

connection.close()

Q19: Create a table in the database for storing user


information.

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

print("Table created successfully!")

connection.commit()
connection.close()

Q20: Write a program that defines a function to retrieve


user data from the users table where the age is greater
than 25.

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)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy