[go: up one dir, main page]

0% found this document useful (0 votes)
16 views48 pages

Ansh Tygai Practical File

The document is a practical file for a Computer Science course, showcasing various Python programming tasks and functions. It includes code examples for counting letters in a string, summing even and odd numbers, file handling operations, and dictionary and list management using binary and CSV files. Each section provides code snippets along with explanations and expected outputs.

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)
16 views48 pages

Ansh Tygai Practical File

The document is a practical file for a Computer Science course, showcasing various Python programming tasks and functions. It includes code examples for counting letters in a string, summing even and odd numbers, file handling operations, and dictionary and list management using binary and CSV files. Each section provides code snippets along with explanations and expected outputs.

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

Computer Science

Practical File
Session 2024-25

Submitted by
Name: Ansh Tyagi
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
Roll No ________
Index:
1. Function

#write a python function that accepts a string and calculate the numer of uppercase and lower
case letters

Python Code:

def count_case_letters(s):
uppercase_count = 0
lowercase_count = 0

for char in s:
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

return uppercase_count, lowercase_count

# Example usage
string = "Python programminG"
upper, lower = count_case_letters(string)
print(f"Uppercase letters: {upper}")
print(f"Lowercase letters: {lower}")

Output:
# writes a python function that accepts listing has parameter and return the sum of all the even no.
and odd no.

Python Code:

def sum_even_odd(numbers):

even_sum = 0

odd_sum = 0

for num in numbers:

if num % 2 == 0:

even_sum += num

else:

odd_sum += num

return even_sum, odd_sum

# Example usage

numbers_list = [1, 2, 3, 4, 5, 6]

even_sum, odd_sum = sum_even_odd(numbers_list)

print(f"Sum of even numbers: {even_sum}")

print(f"Sum of odd numbers: {odd_sum}")

ouput:
# write a python function to find the maximum of three numbers using recursion

Python code:

def max_of_two(x,y):

if x>y:

return x

return y

def max_if_threee(x,y,z):

return max_of_two(x,max_of_two(y,z))

print(max_of_three(8,-4,10))

Output:
# writes a python program to demonstrate the concept of variable length argument to calculate sum
and product of the first 10 numbers

Python code:-

def calculate_sum_and_product(*args):

total_sum = sum(args)

total_product = 1

for num in args:

total_product *= num

return total_sum, total_product

numbers = range(1, 11)

result_sum, result_product = calculate_sum_and_product(*numbers)

print("The sum of the first 10 numbers is:", result_sum)

print("The product of the first 10 numbers is:", result_product)

Output:
#write a user-defined function findname(name) where name is an argument in python to delete
phone number from a dictionary phonebook on the basis of the name,where name is paras

dict= "Ansh tyagi: "123-456-7890", "chairag": "234-567-8901", "paras": "345-678-9012

Python Code:

# Define the function to delete a phone number from the phonebook

def findname(name):

# Check if the name exists in the phonebook

if name in phonebook:

# Delete the entry with the specified name

del phonebook[name]

print(f"{name}'s phone number has been deleted.")

else:

# Inform the user if the name does not exist in the phonebook

print(f"{name} is not found in the phonebook.")

# Example phonebook dictionary

phonebook = {

"Ansh tyagi": "123-456-7890",

"chairag": "234-567-8901",

"paras": "345-678-9012"

# Print the original phonebook

print("Original phonebook:", phonebook)

# Test the function to delete "paras"

findname("paras")
# Print the updated phonebook

print("Updated phonebook:", phonebook)

Output:
2. 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 string

# Open and read the file

with open('story.txt', 'r') as file:

content = file.read()

Count total characters


total_characters = len(content)

Count total lines

with open('story.txt', 'r') as file:

lines = file.readlines()

total_lines = len(lines)

Count total words

total_words = len(content.split())

Count total words in each line

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

Count the number of uppercase, lowercase, and digits in the file

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

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

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

Count the occurrences of "me" and "my" words in the file

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

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

Count the number of lines that start with "the"

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

Count the words that end with "Y"

words_ending_with_y = sum(1 for word in content.split() if word.lower().endswith('y'))


Count the words that start with vowels

vowels = 'aeiou'

words_start_with_vowels = sum(1 for word in content.split() if word[0].lower() in vowels)

. Display the sum of the digits present in the file

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

. Display total vowels and consonants in the file

vowels_count = sum(1 for char in content.lower() if char in vowels)

consonants_count = sum(1 for char in content.lower() if char in string.ascii_lowercase and char not
in vowels)

Copy the content of story.txt to st.txt

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

new_file.write(content)

. Search the given word in the text file and display its occurrences and positions

def search_word(word):

word_positions = []

index = content.lower().find(word.lower())

while index != -1:

word_positions.append(index)

index = content.lower().find(word.lower(), index + 1)

return len(word_positions), word_positions

search_word_input = input("Enter the word to search: ")

word_occurrences, word_positions = search_word(search_word_input)


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

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

# Display the results

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

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

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

print(f"Words per line: {words_per_line}")

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

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

print(f"Digits: {digits_count}")

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

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

print(f"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_start_with_vowels}")

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

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

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

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

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

print(f"Content with 'I' replaced by 's':\n{replaced_content}")


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 process_file(filename):

try:

# Open and read the file

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

content = file.read()

# Split content into words

words = content.split()

# Count total words

total_words = len(words)

# Filter words that have exactly 5 characters

five_char_words = [word for word in words if len(word) == 5]

# Display the results

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

print("Words with exactly 5 characters:")

for word in five_char_words:

print(word)

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('letter.txt')

Output:
Binary File Programs:

# Menu driven program for dictionary operations

Python code:

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"

write_dict_to_file(filename, sample_dict)

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 delete_key_in_dict(data_dict, key):

"""Deletes a key from the dictionary."""

if key in data_dict:

del data_dict[key]

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

else:

print("Key not found.")

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

delete_key_in_dict(data_dict, key)

write_dict_to_file(filename, data_dict)

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:
#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 delete_item_from_list(data_list, index):

"""Deletes an item from the list at a given index."""

if 0 <= index < len(data_list):

del_item = data_list.pop(index)

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


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: ").strip()

if choice == '1':

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

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)

try:

index = int(input("Enter the index of the item 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':

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

search_item_in_list(data_list, item)

elif choice == '5':

display_list(data_list)

try:

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

if 0 <= index < len(data_list):

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

update_item_in_list(data_list, index, new_item)

write_list_to_file(filename, data_list)

else:

print("Invalid index.")

except ValueError:

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

elif choice ==
print("Exiting program.")

break

else:

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

# Main execution for list menu

if __name__ == "__main__":

menu_list()

Output:
C.S.V File program

# # C. S.V file program Menu Driven don't add update and delete:

Python code:

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

sample_data = [

["ID", "Name", "Age", "Salary"],

[1, "Ansh", 16, 70000],

[2, "Paras", 45, 80000],

[3, "Chirag", 28, 60000],

[4, "Dhairya", 32, 75000],

[5, "Zaid", 29, 72000]

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

writer = csv.writer(file)

writer.writerows(sample_data)

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

def read_csv_file(filename):

"""Reads a CSV file and returns its content."""

try:

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


reader = csv.reader(file)

data = list(reader)

return data

except FileNotFoundError:

print("File not found.")

return []

except Exception as e:

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

return []

def write_csv_file(filename, data):

"""Writes data to a CSV file."""

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

writer = csv.writer(file)

writer.writerows(data)

print("Data written to file successfully.")

def display_csv_content(data):

"""Displays the content of the CSV file."""

if not data:

print("The CSV file is empty.")

else:

for row in data:

print(", ".join(map(str, row)))

def search_csv_by_name(data, name):


"""Searches for a name in the CSV data and displays the corresponding row if found."""

for row in data:

if row[1].lower() == name.lower(): # Assuming name is in the second column

print(f"Record found: {', '.join(map(str, row))}")

return

print(f"Name '{name}' not found in the CSV file.")

def add_record_to_csv(filename):

"""Adds a new record to the CSV file."""

id = input("Enter ID: ")

name = input("Enter Name: ")

age = input("Enter Age: ")

salary = input("Enter Salary: ")

new_record = [id, name, age, salary]

data = read_csv_file(filename)

# Add the new record to the existing data

data.append(new_record)

# Write the updated data back to the file

write_csv_file(filename, data)

print(f"Record {new_record} added successfully.")

def menu_csv():

filename = 'data.csv'
initialize_csv_file(filename)

while True:

data = read_csv_file(filename)

print("\nMenu:")

print("1. Add a record")

print("2. Display CSV content")

print("3. Search for a name")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == '1':

add_record_to_csv(filename)

elif choice == '2':

display_csv_content(data)

elif choice == '3':

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

search_csv_by_name(data, name)

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:
3.) MYSQL:-

# 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.
#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.


#Write queries for (i) to (v) and find ouputs for SQL queries

Table:departments

Table:employees

Creating database and tables

i.) INSERT INTO departments (department_name) VALUES ('HR'), ('Finance'), ('IT'), ('Marketing');
ii.) Insert Data into the employees Table:

iii.) Select All Employees with Their Department Names:

iv.) Find Employees Hired after a Specific Date:

v.) Update an Employee's Department:


#Write queries for (i) to (v) and find ouputs for SQL queries

Table: courses

Table: students

Creating database and tables:

i.) Insert Data into students:


ii.) Insert Data into courses:

iii.) Select All Students:

iv.) Select All Courses:

v.) Find Students Enrolled After a Specific Date:


Alter Table clauses on the above table

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.


#Python and Sql Connectivity menu driven program

Python code:

import mysql.connector

from mysql.connector import Error

def connect_to_db():

"""Connect to MySQL database and return the connection object."""

try:

connection = mysql.connector.connect(

host='localhost',

user='root',

password='aksh9906'

if connection.is_connected():

print("Connected to MySQL server.")

return connection

except Error as e:

print(f"Error connecting to MySQL: {e}")

return None

def create_database_and_table(connection):

"""Create database and table if they do not exist."""

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 creating database/table: {e}")

finally:

cursor.close()

def create_record(connection):

"""Insert a new record into the table."""

name = input("Enter name: ")

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

try:

cursor = connection.cursor()

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

connection.commit()

print("Record inserted successfully.")

except Error as e:

print(f"Error inserting record: {e}")

finally:

cursor.close()

def read_records(connection):
"""Read all records from the table."""

try:

cursor = connection.cursor()

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 reading records: {e}")

finally:

cursor.close()

def read_selected_record(connection):

"""Read a specific record from the table based on ID."""

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

try:

cursor = connection.cursor()

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 reading selected record: {e}")

finally:
cursor.close()

def update_record(connection):

"""Update a specific record in the table."""

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 = connection.cursor()

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


new_age, id))

connection.commit()

print("Record updated successfully.")

except Error as e:

print(f"Error updating record: {e}")

finally:

cursor.close()

def delete_record(connection):

"""Delete a specific record from the table based on ID."""

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

try:

cursor = connection.cursor()

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

connection.commit()

print("Record deleted successfully.")

except Error as e:

print(f"Error deleting record: {e}")


finally:

cursor.close()

def main():

connection = connect_to_db()

if connection is None:

return

create_database_and_table(connection)

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

elif choice == '2':

read_records(connection)

elif choice == '3':

read_selected_record(connection)
elif choice == '4':

update_record(connection)

elif choice == '5':

delete_record(connection)

elif choice == '6':

print("Exiting...")

break

else:

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

if connection.is_connected():

connection.close()

print("Connection closed.")

if __name__ == "__main__":

main()
Output:

You might also like