0% found this document useful (0 votes)
39 views50 pages

Akshat Sethi Practical File

This document is a practical file for a Computer Science course, detailing various Python programs and file handling techniques. It includes programs for counting vowels and consonants, summing positive and negative numbers, calculating Fibonacci sequences, and processing text files for various statistics. Additionally, it covers binary file operations for managing movie and student data collections.

Uploaded by

manu pro gaming
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)
39 views50 pages

Akshat Sethi Practical File

This document is a practical file for a Computer Science course, detailing various Python programs and file handling techniques. It includes programs for counting vowels and consonants, summing positive and negative numbers, calculating Fibonacci sequences, and processing text files for various statistics. Additionally, it covers binary file operations for managing movie and student data collections.

Uploaded by

manu pro gaming
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/ 50

Computer Science

Practical File
Session 2024-25

Submitted by
Name: Akshat Sethi
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
Roll No ________
INDEX
Python

Functions Programs:-

# Python program to count the number of vowels and consonants in a


string.

Python Code:-
def count_vowels_consonants(s):

vowels_count = 0

consonants_count = 0

vowels = 'aeiouAEIOU'

for char in s:

if char.isalpha():

if char in vowels:

vowels_count += 1

else:

consonants_count += 1

return vowels_count, consonants_count

# Example usage

string = "Hello World"

vowels, consonants = count_vowels_consonants(string)

print(f"Vowels: {vowels}")

print(f"Consonants: {consonants}")

Output:
# Python program to sum all the positive and negative numbers in a
list.

Python code:-
def sum_positive_negative(numbers):

positive_sum = 0

negative_sum = 0

for num in numbers:

if num > 0:

positive_sum += num

else:

negative_sum += num

return positive_sum, negative_sum

# Example usage

numbers_list = [-10, 20, -30, 40, 50, -60]

positive_sum, negative_sum = sum_positive_negative(numbers_list)

print(f"Sum of positive numbers: {positive_sum}")

print(f"Sum of negative numbers: {negative_sum}")

Output:
#Python Program Fibonacci Sequence using recursion

Python Code:-
def fibonacci(n):

# Base cases

if n == 0:

return 0

elif n == 1:

return 1

# Recursive case: fibonacci(n-1) + fibonacci(n-2)

else:

return fibonacci(n-1) + fibonacci(n-2)

# Test the function

print(fibonacci(6)) # Output: 8

Output:
# Python program to calculate sum and product of the first N numbers using a
loop.

Python Code:-

def calculate_sum_and_product(n):

total_sum = 0

total_product = 1

for num in range(1, n + 1):

total_sum += num

total_product *= num

return total_sum, total_product

# Example usage

n = 10

result_sum, result_product = calculate_sum_and_product(n)

print(f"The sum of the first {n} numbers is: {result_sum}")

print(f"The product of the first {n} numbers is: {result_product}")

Output:-
Python Program to Search for a Key in an In-Memory Dictionary
Python Code:-

# Dictionary storing employee data

employee_dict = {

'101': {'name': 'Alice', 'age': 25, 'position': 'Software Engineer'},

'102': {'name': 'Bob', 'age': 30, 'position': 'Manager'},

'103': {'name': 'Charlie', 'age': 28, 'position': 'Designer'}

# Function to search for a key in the dictionary

def search_employee(emp_id):

if emp_id in employee_dict:

print(f"Employee ID '{emp_id}' found with details: {employee_dict[emp_id]}")

else:

print(f"Employee ID '{emp_id}' not found.")

# Example usage

search_employee('102') # Searching for employee with ID '102'

Output:-
Data File Handling

TEXT FILE Programs:

#WAP that reads a txt file “story.txt" and do the following

count the total characters

Count total lines

Count total words

Count total words in each line

Count the no of uppercase lowercase and digits in file.

Count the occurrence of "me" and "my" words in the file.

Count the no. of lines starts with "the".

Count the word that ends with "Y"

Count the words that start with vowels

Display the sum the digits present in the file

Display total vowel and consonants in the file .

Copy the content of story.txt to st"st.txt"

Search the given word in the text file and display its occurrences and position

Replace "I" with "s" where ever it appears


Python Code:

import os

# Function to check if a character is a vowel

def is_vowel(char):

return char.lower() in 'aeiou'

# Function to process the file and perform the required operations

def process_file(filename):

if not os.path.isfile(filename):

print(f"{filename} does not exist.")

return

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

content = file.read()

# Initialize counters

total_characters = len(content)

total_lines = content.count('\n') + 1 # Counting lines

words = content.split() # Splitting the content into words

total_words = len(words)

uppercase_count = sum(1 for char in content if char.isupper())

lowercase_count = sum(1 for char in content if char.islower())

digit_count = sum(1 for char in content if char.isdigit())

me_count = content.lower().count('me')

my_count = content.lower().count('my')

lines = content.splitlines() # Splitting content into lines


lines_start_with_the = sum(1 for line in lines if line.lower().startswith("the"))

words_ending_with_y = sum(1 for word in words if word.endswith('y') or word.endswith('Y'))

words_starting_with_vowels = sum(1 for word in words if is_vowel(word[0]))

sum_digits = sum(int(char) for char in content if char.isdigit())

vowels_count = sum(1 for char in content if is_vowel(char))

consonants_count = sum(1 for char in content if char.isalpha() and not is_vowel(char))

# Copying the content to a new file "st.txt"

with open('st.txt', 'w') as new_file:

new_file.write(content)

# Search for a given word and display its occurrences and positions

def search_word(word):

occurrences = content.lower().count(word.lower())

positions = []

start = 0

while True:

start = content.lower().find(word.lower(), start)

if start == -1:

break

positions.append(start)

start += len(word)

return occurrences, positions

# Replacing "I" with "s"

content_replaced = content.replace('I', 's')


print("===== File Processing Results =====")

print(f"Total characters: {total_characters}")

print(f"Total lines: {total_lines}")

print(f"Total words: {total_words}")

for i, line in enumerate(lines, 1):

words_in_line = len(line.split())

print(f"Total words in line {i}: {words_in_line}")

print(f"Uppercase letters: {uppercase_count}")

print(f"Lowercase letters: {lowercase_count}")

print(f"Digits: {digit_count}")

print(f"Occurrences of 'me': {me_count}")

print(f"Occurrences of 'my': {my_count}")

print(f"Number of lines starting with 'the': {lines_start_with_the}")

print(f"Words ending with 'y': {words_ending_with_y}")

print(f"Words starting with vowels: {words_starting_with_vowels}")

print(f"Sum of digits in the file: {sum_digits}")

print(f"Total vowels: {vowels_count}")

print(f"Total consonants: {consonants_count}")

search_term = input("Enter a word to search: ")

occurrences, positions = search_word(search_term)

print(f"Occurrences of '{search_term}': {occurrences}")

print(f"Positions of '{search_term}' in the file: {positions}")

print("\nContent after replacing 'I' with 's':\n")

print(content_replaced)
# Example usage

filename = 'story.txt'

process_file(filename)

Output:-
Program to Count Sentences and Display Sentences with Exactly 10
Words

Python Code:
def process_file(filename):

try:

# Open and read the file

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

content = file.read()

# Split content into sentences using '.', '!', and '?'

sentences = [sentence.strip() for sentence in content.replace('!', '.').replace('?', '.').split('.') if sentence]

# Count total sentences

total_sentences = len(sentences)

# Filter sentences that have exactly 10 words

ten_word_sentences = [sentence for sentence in sentences if len(sentence.split()) == 10]

# Display the results

print(f"Total number of sentences: {total_sentences}")

print("Sentences with exactly 10 words:")

for sentence in ten_word_sentences:

print(sentence)

except FileNotFoundError:

print(f"The file {filename} was not found.")

except Exception as e:

print(f"An error occurred: {e}")


# Call the function with the filename

process_file('data.txt')

Output:
Binary File Programs:-

# Menu-Driven Program for List Operations on a Binary File

Python Code:
import pickle

import os

def write_list_to_file(filename, data_list):

"""Writes a list of movies to a binary file."""

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

pickle.dump(data_list, file)

print("Data written to file successfully.")

def read_list_from_file(filename):

"""Reads a list of movies from a binary file."""

if not os.path.exists(filename):

print(f"File '{filename}' does not exist. Creating a new empty file.")

return [] # Return an empty list if file doesn't exist

try:

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

data_list = pickle.load(file)

return data_list

except EOFError:

print("File is empty.")

return [] # Return an empty list if file is empty

def display_list(data_list):

"""Displays the items in the list."""

if not data_list:

print("The list is empty.")

else:

print("\nMovies in the Collection:")

for i, movie in enumerate(data_list, start=1):


print(f"{i}. {movie['title']} (Director: {movie['director']}, Year: {movie['year']})")

def search_item_in_list(data_list, title):

"""Searches for a movie by title and displays its index if found."""

for index, movie in enumerate(data_list):

if movie['title'].lower() == title.lower():

print(f"Movie '{title}' found at position {index + 1}.")

return

print(f"Movie '{title}' not found in the collection.")

def update_item_in_list(data_list, index, new_movie):

"""Updates a movie in the list at a given index."""

if 0 <= index < len(data_list):

old_movie = data_list[index]

data_list[index] = new_movie

print(f"Movie '{old_movie['title']}' updated to '{new_movie['title']}'.")

else:

print("Invalid index.")

def delete_item_from_list(data_list, index):

"""Deletes a movie from the list at a given index."""

if 0 <= index < len(data_list):

del_movie = data_list.pop(index)

print(f"Movie '{del_movie['title']}' deleted successfully.")

else:

print("Invalid index.")

def menu_list():

filename = 'movies_data.bin'

data_list = read_list_from_file(filename)

while True:

print("\nMenu:")

print("1. Add movie to collection")

print("2. Display movie collection")


print("3. Delete movie from collection")

print("4. Search for a movie")

print("5. Update a movie")

print("6. Exit")

choice = input("Enter your choice: ").strip()

if choice == '1':

title = input("Enter movie title: ").strip()

director = input("Enter director name: ").strip()

year = input("Enter release year: ").strip()

data_list.append({'title': title, 'director': director, 'year': year})

write_list_to_file(filename, data_list)

print(f"Movie '{title}' added successfully.")

elif choice == '2':

display_list(data_list)

elif choice == '3':

display_list(data_list)

try:

index = int(input("Enter the index of the movie to delete: ").strip()) - 1

delete_item_from_list(data_list, index)

write_list_to_file(filename, data_list)

except ValueError:

print("Invalid input. Please enter a number.")

elif choice == '4':

title = input("Enter movie title to search: ").strip()

search_item_in_list(data_list, title)

elif choice == '5':

display_list(data_list)

try:
index = int(input("Enter the index of the movie to update: ").strip()) - 1

if 0 <= index < len(data_list):

new_title = input("Enter new movie title: ").strip()

new_director = input("Enter new director name: ").strip()

new_year = input("Enter new release year: ").strip()

update_item_in_list(data_list, index, {'title': new_title, 'director': new_director, 'year':


new_year})

write_list_to_file(filename, data_list)

else:

print("Invalid index.")

except ValueError:

print("Invalid input. Please enter a number.")

elif choice == '6':

print("Exiting program.")

break

else:

print("Invalid choice, please try again.")

# Main execution for movie menu

if __name__ == "__main__":

menu_list()
Output:
#File Content for Dictionary Operations: dict_operations.py

Python Code:
# student_management.py

import pickle

import os

def initialize_student_file(filename):

"""Initialize the student binary file with sample data if it doesn't exist."""

if not os.path.isfile(filename):

sample_students = {

"1001": {"name": "Alice", "age": "20", "grade": "A"},

"1002": {"name": "Bob", "age": "21", "grade": "B"}

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

pickle.dump(sample_students, file)

print(f"Student binary file '{filename}' created and initialized with sample data.")

def write_students_to_file(filename, student_dict):

"""Writes the student dictionary to a binary file."""

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

pickle.dump(student_dict, file)

print("Data written to file successfully.")

def read_students_from_file(filename):

"""Reads the student dictionary from a binary file."""

try:

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

student_dict = pickle.load(file)

return student_dict
except FileNotFoundError:

print("File not found. Returning an empty dictionary.")

return {}

except EOFError:

print("File is empty. Returning an empty dictionary.")

return {}

def display_students(student_dict):

"""Displays all student details in the dictionary."""

if not student_dict:

print("No student data found.")

else:

print("\nStudent Details:")

for student_id, details in student_dict.items():

print(f"ID: {student_id}, Name: {details['name']}, Age: {details['age']}, Grade: {details['grade']}")

def search_student_by_id(student_dict, student_id):

"""Searches for a student by their ID and displays their details if found."""

if student_id in student_dict:

student = student_dict[student_id]

print(f"Student found - ID: {student_id}, Name: {student['name']}, Age: {student['age']}, Grade:


{student['grade']}")

else:

print(f"Student with ID '{student_id}' not found.")

def menu_student():

filename = 'student_data.bin'

initialize_student_file(filename)

student_dict = read_students_from_file(filename)

while True:

print("\nMenu:")

print("1. Add or update student details")


print("2. Display all students")

print("3. Delete a student")

print("4. Search for a student by ID")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':

student_id = input("Enter student ID: ")

name = input("Enter student name: ")

age = input("Enter student age: ")

grade = input("Enter student grade: ")

student_dict[student_id] = {"name": name, "age": age, "grade": grade}

write_students_to_file(filename, student_dict)

print(f"Student ID '{student_id}' added/updated successfully.")

elif choice == '2':

display_students(student_dict)

elif choice == '3':

student_id = input("Enter the student ID to delete: ")

if student_id in student_dict:

del student_dict[student_id]

write_students_to_file(filename, student_dict)

print(f"Student ID '{student_id}' deleted successfully.")

else:

print("Student ID not found.")

elif choice == '4':

student_id = input("Enter the student ID to search: ")

search_student_by_id(student_dict, student_id)

elif choice == '5':

print("Exiting program.")

break
else:

print("Invalid choice, please try again.")

# Main execution for student menu

if __name__ == "__main__":

menu_student

Output:
C.S.V File Programs:

# C. S.V file program Menu Driven complete program

Python Code:

# library_management.py

import csv

import os

def initialize_csv_file(filename):

"""Initialize the CSV file with sample book data if it doesn't exist."""

if not os.path.isfile(filename):

with open(filename, 'w', newline='') as file:

writer = csv.writer(file)

# Write sample header and data

writer.writerow(["Book ID", "Title", "Author", "Year"])

writer.writerow([101, "The Great Gatsby", "F. Scott Fitzgerald", 1925])

writer.writerow([102, "1984", "George Orwell", 1949])

print(f"CSV file '{filename}' created and initialized with sample book data.")

def display_csv(filename):

"""Display all records in the CSV file."""

if not os.path.isfile(filename):

print("File not found.")

return

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

reader = csv.reader(file)

for row in reader:

print(", ".join(row))
def add_record(filename):

"""Add a new book record to the CSV file."""

book_id = input("Enter Book ID: ")

title = input("Enter Book Title: ")

author = input("Enter Author: ")

year = input("Enter Publication Year: ")

with open(filename, 'a', newline='') as file:

writer = csv.writer(file)

writer.writerow([book_id, title, author, year])

print("Book record added successfully.")

def search_record(filename):

"""Search for a book in the CSV file by Book ID."""

id_to_search = input("Enter Book ID to search: ")

found = False

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

reader = csv.reader(file)

for row in reader:

if row[0] == id_to_search:

print("Book record found:")

print(", ".join(row))

found = True

break

if not found:

print("Book record not found.")

def menu_csv():

filename = 'library.csv'

initialize_csv_file(filename)

while True:
print("\nLibrary Menu:")

print("1. Display all books")

print("2. Add a book")

print("3. Search for a book")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':

display_csv(filename)

elif choice == '2':

add_record(filename)

elif choice == '3':

search_record(filename)

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid choice, please try again.")

# Main execution for CSV menu

if __name__ == "__main__":

menu_csv()
Output:
MYSQL: - SINGLE TABLE BASED-1
# Do SQL Queries Consider the following table:

i) Create the above table in the database DB1.

ii) Add all the records in the above table

iii) Display all records.


iv) Display activity name, Participants Num from the above table.

v) Display those activities where participant’s num is above 10.

vi) Display all records where prize money is less than 10000.
SINGLE TABLE BASED- 2

#Consider the following tables RESORT:

i) Create the above table in the database DB1.

ii) Add all the records in the above table.


iii) Display all records.

iv) Display Resorts code that exists in "Goa".

v) Display records that rent falls in 10000-13000.


TWO TABLE BASED – 1
Table: Customer and TRANSACTION
# Do SQL Queries Consider the following tables:

Creating Database and tables:-


i.) Write a query to select the maximum and minimum balance from the
CUSTOMER table for male customers (Gender = 'M').

ii.) Write a query to select the total sum of Amount, grouped by transaction
Type, from the TRANSACTION table.
iii.)Write a query to select the customer name (Cname), transaction date (Tdate),
and transaction amount (Amount) from the CUSTOMER and TRANSACTION
tables where the account numbers match (C.ACNO = T.ACNO) and the transaction
type is 'CREDIT'.
TWO TABLE BASED – 2
Tables: CARDEN and CUSTOMER:

Creating database and tables:


(i) Display the names of all the silver coloured cars.

(ii) Display name of car, make, and capacity of cars in descending order of
their sitting capacity.

(iii) Display the highest charges at which a vehicle can be hired from
CARDEN.
(iv) Display the customer name and the corresponding name of the cars hired by them.

(v) Display the total number of cars in each color.


ALTER TABLE
Alter Table clauses on the above table Resort:
a) Add a column to the above table.

b) Change the Name of any Column.


c) Modify the data type of any column.

d) Remove any Column.

e) Add a primary key to the above table.


Cartesian product (Cross Join) and Natural Join in SQL:
Cartesian product: Cross Joining CARDEN from CUSTOMER

Output:

Natural Join:
FROM CARDEN NATURAL JOINING CUSTOMER;

Output:
PYTHON AND SQL CONNECTIVITY Program:-
#Python and Sql Connectivity menu driven program
Python Code:
import mysql.connector

from mysql.connector import Error

def connect_to_db():

try:

connection = mysql.connector.connect(

host='localhost',

user='root',

password='aksh9906' # Updated password here

if connection.is_connected():

print("Connected to MySQL server.")

return connection

except Error as e:

print(f"Error: {e}")

return None

def create_database_and_table(connection):

try:

cursor = connection.cursor()

cursor.execute("CREATE DATABASE IF NOT EXISTS account_db")

cursor.execute("USE account_db")

cursor.execute("""

CREATE TABLE IF NOT EXISTS accounts (

id INT AUTO_INCREMENT PRIMARY KEY,

username VARCHAR(255) NOT NULL,


email VARCHAR(255) NOT NULL,

password VARCHAR(255) NOT NULL

""")

print("Database and table setup complete.")

except Error as e:

print(f"Error: {e}")

def create_sample_data(cursor):

sample_accounts = [

("chirag.aggarwal", "[email protected]", "password123"),

("akshat.sethi", "[email protected]", "password456"),

("bhavya.mehta", "[email protected]", "password789"),

("bhavya.jain", "[email protected]", "password1011")

try:

cursor.executemany("INSERT INTO accounts (username, email, password) VALUES (%s, %s, %s)",
sample_accounts)

print("Sample data inserted successfully.")

except Error as e:

print(f"Error: {e}")

def create_account(cursor):

username = input("Enter username: ")

email = input("Enter email: ")

password = input("Enter password: ")

try:

cursor.execute("INSERT INTO accounts (username, email, password) VALUES (%s, %s, %s)",

(username, email, password))

print("Account created successfully.")


except Error as e:

print(f"Error: {e}")

def read_accounts(cursor):

try:

cursor.execute("SELECT * FROM accounts")

rows = cursor.fetchall()

print("\nAll Accounts:")

for row in rows:

print(f"ID: {row[0]}, Username: {row[1]}, Email: {row[2]}")

except Error as e:

print(f"Error: {e}")

def read_selected_account(cursor):

id = int(input("Enter the ID of the account to display: "))

try:

cursor.execute("SELECT * FROM accounts WHERE id = %s", (id,))

row = cursor.fetchone()

if row:

print(f"ID: {row[0]}, Username: {row[1]}, Email: {row[2]}")

else:

print("Account not found.")

except Error as e:

print(f"Error: {e}")

def update_account(cursor):

id = int(input("Enter the ID of the account to update: "))

new_username = input("Enter the new username: ")

new_email = input("Enter the new email: ")

new_password = input("Enter the new password: ")

try:
cursor.execute("UPDATE accounts SET username = %s, email = %s, password = %s WHERE id = %s",

(new_username, new_email, new_password, id))

print("Account updated successfully.")

except Error as e:

print(f"Error: {e}")

def delete_account(cursor):

id = int(input("Enter the ID of the account to delete: "))

try:

cursor.execute("DELETE FROM accounts WHERE id = %s", (id,))

print("Account deleted successfully.")

except Error as e:

print(f"Error: {e}")

def main():

connection = connect_to_db()

if connection is None:

return

create_database_and_table(connection)

cursor = connection.cursor()

# Insert sample data into the database

create_sample_data(cursor)

connection.commit()

while True:

print("\nMenu:")

print("1. Create Account")

print("2. Read All Accounts")

print("3. Read Selected Account")

print("4. Update Account")

print("5. Delete Account")

print("6. Exit")
choice = input("Enter your choice: ")

if choice == '1':

create_account(cursor)

connection.commit()

elif choice == '2':

read_accounts(cursor)

elif choice == '3':

read_selected_account(cursor)

elif choice == '4':

update_account(cursor)

connection.commit()

elif choice == '5':

delete_account(cursor)

connection.commit()

elif choice == '6':

print("Exiting...")

break

else:

print("Invalid choice. Please try again.")

cursor.close()

connection.close()

if __name__ == "__main__":

main()
Output:-

You might also like