0% found this document useful (0 votes)
55 views52 pages

Computer Scinece Practical File

computer Scinece practical file for class 12

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)
55 views52 pages

Computer Scinece Practical File

computer Scinece practical file for class 12

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/ 52

Computer Science

Practical File
Session 2024-25

Submitted by
Name: Kartik gupta
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
School: Vivekanand public school
Roll No:
INDEX
Functions- INT
#Write a function that converts euros to Indian rupees using
a given conversion rate.
Python code:
def convert_to_rupees(euroAmount, conversionRate):

amountInRupee = euroAmount * conversionRate

return amountInRupee

amount = float(input("Enter the amount in euros: "))

conversion_rate = float(input("Enter the conversion rate: "))

converted_amount = convert_to_rupees(amount, conversion_rate)

print(f"Amount in Rupees: {converted_amount}")

Output:
FUNCTION - STRING
#Write a function that counts the number of
consonants in a string.

Python Code:
def count_consonants(string):

consonants = "bcdfghjklmnpqrstvwxyz"

count = sum(1 for char in string.lower() if char in consonants)

return count

msg = input("Enter a string: ")

print("Number of consonants:", count_consonants(msg))

Output:
FUNCTION - LIST
#Write a function to find the maximum and minimum
number from a list.

Python Code:
def find_max_min(numbers):

return max(numbers), min(numbers)

myList = [int(input("Enter a number: ")) for _ in range(int(input("How


many numbers?: ")))]

print("Max and Min:", find_max_min(myList))

Output:
FUNCTION - TUPLE
#Create a function that checks a valid email-password
pair.
Python code:

def check_login(users, passwords, inputUser, inputPassword):

if inputUser in users and inputPassword ==


passwords[users.index(inputUser)]:

return "Login Successful"

return "Login Failed"

usernames = ("kartik", "user2")

passwords = ("kartik 9906", "pass2")

u = input("Enter username: ")

p = input("Enter password: ")

print(check_login(usernames, passwords, u, p))

Output:
FUNCTION - DICTIONARY

# Write a function that modifies an existing dictionary


entry.

Python Code:
def update_dict(data, key, newValue):

data[key] = newValue

info = {"Name": "Ansh Tyagi", "Class": "XII", "RollNo": 42}

print("Before update:", info)

key = input("Enter the key to update: ")

new_value = input("Enter the new value: ")

update_dict(info, key, new_value)

print("After update:", info)

Output:
DATA FILE HANDLING - TEXT FILES
#WAP that reads a txt file “story.txt" and do the following
1. ) count the total characters
2.) Count total lines
3.) Count total words
4.) Count total words in each line
5.) Count the no of uppercase lowercase and digits in file.
6.) Count the occurrence of "me" and "my" words in the file.
7.) Count the no. of lines starts with "the".
8.) Count the word that ends with "Y"
9.) Count the words that starts with vowels
10. ) display the sum the digits present in the file
11.) Display total vowel and consonants in the file .
12.) copy the content of story.txt to st"st.txt"
13.) Search the given word in the text file and display its
occurrences and position
14.) Replace "I" with "s" where ever it appears.
Python Code:
def text_file_analysis(file_path):

try:

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

content = file.read()

file.seek(0)

lines = file.readlines()

# 1. Count total characters

total_characters = len(content)

# 2. Count total lines

total_lines = len(lines)

# 3. Count total words

words = content.split()

total_words = len(words)

# 4. Count total words in each line

words_in_each_line = [len(line.split()) for line in lines]

# 5. Count uppercase, lowercase, and digits

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


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

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

# 6. Count occurrences of "me" and "my"

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

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

# 7. Count lines starting with "the"

lines_starting_with_the = sum(1 for line in lines if


line.lower().startswith('the'))

# 8. Count words ending with "Y"

words_ending_with_y = sum(1 for word in words if


word.lower().endswith('y'))

# 9. Count words starting with vowels

vowels = ('a', 'e', 'i', 'o', 'u')

words_starting_with_vowel = sum(1 for word in words if


word.lower().startswith(vowels))

# 10. Sum of digits present in the file

digits_in_content = [int(c) for c in content if c.isdigit()]

sum_of_digits = sum(digits_in_content)
# 11. Count total vowels and consonants

vowel_count = sum(1 for c in content.lower() if c in vowels)

consonant_count = sum(1 for c in content.lower() if c.isalpha() and c not in


vowels)

# 12. Copy content to "st.txt"

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

st_file.write(content)

# 13. Search for a word and display occurrences and positions

search_word = input("Enter the word to search: ").strip()

word_occurrences = 0

word_positions = []

for idx, word in enumerate(words):

if word.strip('.,!?;"\'').lower() == search_word.lower():

word_occurrences += 1

word_positions.append(idx + 1) # Position starts from 1

# 14. Replace "I" with "s" wherever it appears

replaced_content = content.replace('I', 's').replace('i', 's')

with open('story_replaced.txt', 'w') as replaced_file:

replaced_file.write(replaced_content)

# Displaying all results


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

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

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

print(f"Words in each line: {words_in_each_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"Lines starting with 'the': {lines_starting_with_the}")

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

print(f"Words starting with a vowel: {words_starting_with_vowel}")

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

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

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

print(f"Occurrences of '{search_word}': {word_occurrences}")

print(f"Positions of '{search_word}': {word_positions}")

print("Content copied to 'st.txt'")

print("Content with 'I' replaced by 's' saved to 'story_replaced.txt'")


except FileNotFoundError:

print(f"Error: The file '{file_path}' was not found.")

except Exception as e:

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

# Main execution

if __name__ == "__main__":

text_file_path = 'story.txt'

text_file_analysis(text_file_path)

Output:
# Write a Python program that reads a file named letter.txt,
counts all the words, and displays the words that have
exactly 5 characters.

Python Code:
def count_five_letter_words(file_path):

try:

# Open the file in read mode

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

content = file.read()

# Split the content into words

words = content.split()

# Count total words

total_words = len(words)

print(f"Total words in the file: {total_words}")

# Find words that have exactly 5 characters (ignoring punctuation)

five_letter_words = [word.strip('.,!?;"\'()') for word in words if


len(word.strip('.,!?;"\'()')) == 5]

# Display words that have exactly 5 characters

print(f"Words with exactly 5 characters: {five_letter_words}")


print(f"Total words with exactly 5 characters:
{len(five_letter_words)}")

except FileNotFoundError:

print(f"Error: The file '{file_path}' was not found.")

except Exception as e:

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

# Main execution

if __name__ == "__main__":

text_file_path = 'letter.txt'

count_five_letter_words(text_file_path)

Output:
Function-argument
# Function that takes a list as an argument and prints
each element
Python Code:
# Function that takes a list as an argument and prints each element

def print_list_elements(my_list):

"""This function prints each element of the list."""

for element in my_list:

print(element)

# Function that takes a list and returns the sum of its elements

def sum_of_list(my_list):

"""This function returns the sum of all elements in the list."""

return sum(my_list)

# Function that appends an element to the list

def append_to_list(my_list, item):

"""This function appends a new item to the list."""

my_list.append(item)

# Passing a list as an argument

numbers = [10, 20, 30, 40]


# Print the elements of the list

print("List elements:")

print_list_elements(numbers)

# Calculate the sum of list elements

total_sum = sum_of_list(numbers)

print("\nSum of list elements:", total_sum)

# Append a new item to the list

append_to_list(numbers, 50)

print("\nList after appending 50:")

print_list_elements(numbers)

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

Python Code:
import pickle

def write_list_to_file(filename, data_list):

"""Writes a list 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 from a binary file."""

try:

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

data_list = pickle.load(file)

return data_list

except FileNotFoundError:

print("File not found.")

return []
except EOFError:

print("File is empty.")

return []

def display_list(data_list):

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

if not data_list:

print("The list is empty.")

else:

print("\nList Contents:")

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

print(f"{i}. {item}")

def search_item_in_list(data_list, item):

"""Searches for an item in the list and displays its index if found."""

if item in data_list:

index = data_list.index(item)

print(f"Item '{item}' found at position {index + 1}.")

else:

print(f"Item '{item}' not found in the list.")

def update_item_in_list(data_list, index, new_item):

"""Updates an item in the list at a given index."""

if 0 <= index < len(data_list):


old_item = data_list[index]

data_list[index] = new_item

print(f"Item '{old_item}' updated to '{new_item}'.")

else:

print("Invalid index.")

def menu_list():

filename = 'list_data.bin'

data_list = read_list_from_file(filename)

while True:

print("\nMenu:")

print("1. Add item to list")

print("2. Display list")

print("3. Delete item from list")

print("4. Search for an item")

print("5. Update an item")

print("6. Exit")

choice = input("Enter your choice: ")

if choice == '1':

item = input("Enter item to add: ")

data_list.append(item)

write_list_to_file(filename, data_list)

print(f"Item '{item}' added successfully.")

elif choice == '2':


display_list(data_list)

elif choice == '3':

display_list(data_list)

index = int(input("Enter the index of the item to delete: ")) - 1

if 0 <= index < len(data_list):

del_item = data_list.pop(index)

write_list_to_file(filename, data_list)

print(f"Item '{del_item}' deleted successfully.")

else:

print("Invalid index.")

elif choice == '4':

item = input("Enter item to search: ")

search_item_in_list(data_list, item)

elif choice == '5':

display_list(data_list)

index = int(input("Enter the index of the item to update: ")) - 1

if 0 <= index < len(data_list):

new_item = input("Enter the new item: ")

update_item_in_list(data_list, index, new_item)

write_list_to_file(filename, data_list)

else:

print("Invalid index.")

elif choice == '6':

print("Exiting program.")
break

else:

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

# Main execution for list menu

if __name__ == "__main__":

menu_list()

Output:
#File Content for Dictionary Operations:
dict_operations.py

Python Code:
# dict_operations.py

import pickle

import os

def initialize_dict_file(filename):

"""Initialize the dictionary binary file with sample data if it doesn't


exist."""

if not os.path.isfile(filename):

sample_dict = {

"name": "Alice",

"age": "30",

"city": "Wonderland"

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

pickle.dump(sample_dict, file)

print(f"Dictionary binary file '{filename}' created and initialized with


sample data.")
def write_dict_to_file(filename, data_dict):

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

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

pickle.dump(data_dict, file)

print("Data written to file successfully.")

def read_dict_from_file(filename):

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

try:

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

data_dict = pickle.load(file)

return data_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_dict(data_dict):

"""Displays all key-value pairs in the dictionary."""

if not data_dict:

print("The dictionary is empty.")


else:

print("\nDictionary Contents:")

for key, value in data_dict.items():

print(f"{key}: {value}")

def search_key_in_dict(data_dict, key):

"""Searches for a key in the dictionary and displays its value if found."""

if key in data_dict:

print(f"Key '{key}' found with value: {data_dict[key]}")

else:

print(f"Key '{key}' not found in the dictionary.")

def menu_dict():

filename = 'dict_data.bin'

initialize_dict_file(filename)

data_dict = read_dict_from_file(filename)

while True:

print("\nMenu:")

print("1. Add or update key-value pair")

print("2. Display dictionary")

print("3. Delete key from dictionary")

print("4. Search for a key")

print("5. Exit")

choice = input("Enter your choice: ")


if choice == '1':

key = input("Enter key: ")

value = input("Enter value: ")

data_dict[key] = value

write_dict_to_file(filename, data_dict)

print(f"Key '{key}' added/updated successfully.")

elif choice == '2':

display_dict(data_dict)

elif choice == '3':

key = input("Enter the key to delete: ")

if key in data_dict:

del data_dict[key]

write_dict_to_file(filename, data_dict)

print(f"Key '{key}' deleted successfully.")

else:

print("Key not found.")

elif choice == '4':

key = input("Enter the key to search: ")

search_key_in_dict(data_dict, key)

elif choice == '5':

print("Exiting program.")

break

else:

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


# Main execution for dictionary menu

if __name__ == "__main__":

menu_dict()

Output:
File handling –C.S.V File

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

Python Code:
# csv_operations.py

import csv

import os

def initialize_csv_file(filename):

"""Initialize the CSV file with sample 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(["ID", "Name", "Age", "City"])

writer.writerow([1, "Alice", 30, "Wonderland"])

writer.writerow([2, "Bob", 25, "Builderland"])

print(f"CSV file '{filename}' created and initialized with sample 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 record to the CSV file."""

id = input("Enter ID: ")

name = input("Enter Name: ")

age = input("Enter Age: ")

city = input("Enter City: ")

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

writer = csv.writer(file)

writer.writerow([id, name, age, city])

print("Record added successfully.")

def search_record(filename):

"""Search for a record in the CSV file by ID."""


id_to_search = input("Enter ID of the record 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("Record found:")

print(", ".join(row))

found = True

break

if not found:

print("Record not found.")

def menu_csv():

filename = 'records.csv'

initialize_csv_file(filename)

while True:

print("\nMenu:")

print("1. Display all records")

print("2. Add a record")

print("3. Search for a record")

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

BankDB Tables:

Table: TRANSACT
TRNO ANO AMOUNT TYPE DOT

Creating database and tables:


Inserting Values into BankDB:

ACCOUNT Table:

TRANSACT Table:

Queries on BankDB:
(i) To display details of all transactions of TYPE Withdraw from
TRANSACT table:
(ii) To display ANO and AMOUNT of all Deposit and Withdrawals done
in the month of ‘May’ 2017:

(iii) To display the first date of transaction (DOT) from table


TRANSACT for Account having ANO as 102:

(iv) To display ANO, ANAME, AMOUNT, and DOT of those persons from
ACCOUNT and TRANSACT tables that have done transactions less than
or equal to 3000:

(v) To exclude certain addresses from ACCOUNT:


TWO TABLE BASED – 2
TravelDB Tables:

Creating database and tables:


Inserting Values into TravelDB:

VEHICLE Table:

TRAVEL Table:

Queries on TravelDB:
(i) Display CNO, CNAME, and TRAVELDATE from the TRAVEL table in
descending order of CNO:
(ii) Display the CNAME of all customers from the TRAVEL table who
are traveling by vehicle with code V01 or V02:

(iii) Display the CNO and CNAME of those customers from the TRAVEL
table who traveled between certain dates:

(iv) Display all details from the TRAVEL table for customers who have
travelled more than 120 KM, ordered by NOP:

(v) Group and count by VCODE:


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 Departments From employees
Output:

Natural Join:
FROM Employees NATURAL Joining Departments;

Output:
PYTHON AND SQL CONNECTIVITY

#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='1234'

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

cursor.execute("USE my_database")

cursor.execute("""

CREATE TABLE IF NOT EXISTS my_table (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255) NOT NULL,

age INT NOT NULL

""")

print("Database and table setup complete.")

except Error as e:

print(f"Error: {e}")

def create_record(cursor):

name = input("Enter name: ")


age = int(input("Enter age: "))

try:

cursor.execute("INSERT INTO my_table (name, age) VALUES (%s, %s)",


(name, age))

print("Record inserted successfully.")

except Error as e:

print(f"Error: {e}")

def read_records(cursor):

try:

cursor.execute("SELECT * FROM my_table")

rows = cursor.fetchall()

print("\nAll Records:")

for row in rows:

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

except Error as e:

print(f"Error: {e}")

def read_selected_record(cursor):

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

try:

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

row = cursor.fetchone()

if row:

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


else:

print("Record not found.")

except Error as e:

print(f"Error: {e}")

def update_record(cursor):

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

new_name = input("Enter the new name: ")

new_age = int(input("Enter the new age: "))

try:

cursor.execute("UPDATE my_table SET name = %s, age = %s WHERE id =


%s", (new_name, new_age, id))

print("Record updated successfully.")

except Error as e:

print(f"Error: {e}")

def delete_record(cursor):

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

try:

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

print("Record 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()

while True:

print("\nMenu:")

print("1. Create Record")

print("2. Read All Records")

print("3. Read Selected Record")

print("4. Update Record")

print("5. Delete Record")

print("6. Exit")

choice = input("Enter your choice: ")

if choice == '1':

create_record(cursor)

connection.commit()

elif choice == '2':

read_records(cursor)

elif choice == '3':

read_selected_record(cursor)

elif choice == '4':

update_record(cursor)

connection.commit()
elif choice == '5':

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