0% found this document useful (0 votes)
22 views29 pages

Practical File 12TH CS

This document is a practical file for a computer science course, detailing various Python programming tasks and SQL commands. It includes an index of practical exercises, such as creating functions, file handling, and database operations. Additionally, it contains an acknowledgment section thanking the teacher and others for their support in completing the file.

Uploaded by

Ashutosh Gamer
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)
22 views29 pages

Practical File 12TH CS

This document is a practical file for a computer science course, detailing various Python programming tasks and SQL commands. It includes an index of practical exercises, such as creating functions, file handling, and database operations. Additionally, it contains an acknowledgment section thanking the teacher and others for their support in completing the file.

Uploaded by

Ashutosh Gamer
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/ 29

SCHOLARS HOME

INTERNATIONAL SCHOOL
COMPUTER SCIENCE
PRACTICAL FILE
NAME-
CLASS-
ROLL NO. –

SUBMITTED TO-
MS.PRAMOD KUMAR SIR

1|P ag e
INDEX
S. Date Practical Name Pg.n sign
No.
1. 5/7/24 Write a python program using a function to 4-4
print a factorial number series from n to m
numbers
2. 20/7/24 Write a python program to accept user 5-5
name “Admin” as default argument in
password 123 entered by user to allow login
into the system
3. 2/8/24 Write a program to replace all spaces from 6-6
text with – (dash) from this file into text.
4. 24/8/24 Write a python program to implement a 7-8
stack using list.
5. 18/9/24 Write a random number generator that 9-9
generates random numbers between 1 and
6 (simulates a dice).
6. 4/10/24 Create a csv file by entering user id and 10-11
password, read and search the password for
given user id.
7. 27/10/24 Python program to create a binary file with 12-13
roll no. and name search for a given roll no.
and display name.
8. 26/11/24 Python program to count and display no. of 14-14
vowels consonants uppercase and lower
case characters
9. 4/12/24 Create a student table and insert data 15-19
implement the following SQL commands on
the student table: ALTER table to add new
attributes/modify data type/drop attribute
UPDATE table to modify data ORDER By to
display data in ascending/descending order
DELETE to remove tuple(s) GROUP BY and
find the min, max, sum, count and average.
10. 6/12/24 Read a csv file top 5 csv and print those with 20-20
top defumiter ignore first row header to
print in tabular form.
11. 8/12/24 Create a text file intro.txt in python and ask 21-21
the user to write a single link text by user
input
2|P ag e
12. 11/12/24 Write a program to count the no of times 22-23
starting with a, b, and c form the file
myfile.txt.
13. 12/12/24 Write a python program to demonstrate the 24-24
concept of variable length argument to
calculate product and power of the first 10
numbers.
14. 15/12/24 Modify the program and display customer details25-26
based on the following menu:
(i)city (ii)name (iii)bill amount (iv) category
15. 16/12/24 Create a binary file client.dat to hold records 27-28
like client ID, client name and address using
the dictionary write functions to write data,
read them and print on the screen.

3|P ag e
Acknowledgement
It is with great pleasure, I express my gratitude to
those who helped me a long way in completing my
practical file. I whole heartedly thank my computer
teacher Mr. Pramod Kumar for his guidance and
support.
I would also like to express my deep sense of
gratitude to the principal of our school, teachers and
friends for their inspiration and constant help during
the making of this practical file. Finally, I would like to
thank CBSE for this wonderful opportunity.

4|P ag e
Practical 1
Write a python program using a function to print a factorial number series from n to m
numbers.
Ans):-
def factorial(num):
# Function to calculate the factorial of a number
if num == 0 or num == 1:
return 1
else:
fact = 1
for i in range(2, num + 1):
fact *= i
return fact
def factorial_series(n, m):
# Function to print the factorial series from n to m
for i in range(n, m + 1):
print("Factorial of {i} is {factorial(i)}")
# Input values for n and m
n = int(input("Enter the starting number (n): "))
m = int(input("Enter the ending number (m): "))
# Call the factorial_series function
factorial_series(n,m)

5|P ag e
Practical 2
Write a python program to accept user name “Admin” as default argument in
password 123 entered by user to allow login into the system.
Ans):-
def login(username="Admin", password="123"):
# Accepting user input for username and password
entered_username = input("Enter username: ")
entered_password = input("Enter password: ")
# Check if entered credentials match the default ones
if entered_username == username and entered_password == password:
print("Login successful!")
else:
print("Invalid username or password. Please try again.")
# Call the login function
login()

6|P ag e
Practical 3
Write a program to replace all spaces from text with – (dash) from this file into text.
Ans):-
def replace_spaces_with_dashes(file_path):
try:
# Open the file in read mode
with open(file_path, 'r') as file:
text = file.read()
# Replace all spaces with dashes
modified_text = text.replace(" ", "-")
# Open the file in write mode to overwrite the content
with open(file_path, 'w') as file:
file.write(modified_text)
print("Spaces replaced with dashes successfully.")
except FileNotFoundError:
print(f"Error: The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Specify the path to the text file
file_path = input("Enter the path to the text file: ")
# Call the function to replace spaces with dashes
replace_spaces_with_dashes(file_path)

7|P ag e
PRACTICAL 4
Write a python program to implement a stack using list.
Ans):-
class Stack:
def __init__(self):
# Initialize the stack as an empty list
self.stack = []
def is_empty(self):
# Check if the stack is empty
return len(self.stack) == 0
def push(self, item):
# Add an item to the top of the stack
self.stack.append(item)
print(f"Item {item} pushed to stack")
def pop(self):
# Remove and return the top item of the stack
if not self.is_empty():
popped_item = self.stack.pop()
print(f"Item {popped_item} popped from stack")
return popped_item
else:
print("Stack is empty. Cannot pop.")
return None
def peek(self):
# Return the top item without removing it
if not self.is_empty():
return self.stack[-1]
else:
print("Stack is empty.")

8|P ag e
return None
def size(self):
# Return the size of the stack
return len(self.stack)
def display(self):
# Display the current stack
print("Current stack:", self.stack)
# Example Usage
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.display() # Display stack after pushing items
stack.pop() # Pop an item
stack.display() # Display stack after popping an item
print("Top item is:", stack.peek()) # Peek at the top item
print("Stack size is:", stack.size()) # Get the stack size

9|P ag e
PRACTICAL 5
Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
Ans):-
import random
def roll_dice():
# Generate a random number between 1 and 6 (inclusive)
return random.randint(1, 6)
# Simulate rolling the dice
print("Rolling the dice...")
result = roll_dice()
print(f"The result of the dice roll is: {result}")

10 | P a g e
PRACTICAL 6
Create a csv file by entering user id and password, read and search the password for
given user id.
Ans):-
import csv
def write():
f=open("details.csv","w",newline='')
wo=csv.writer(f)
wo.writerow(["userId","Password"])
while True:
u_id = input ("enter userId:")
pswd=input("enter password:")
data=[u_id,pswd]
wo.writerow(data)
ch=input("do you want to enter more (Y/N)")
if ch in 'Nn':
break
f.close()
def read():
f=open("details.csv","r")
ro=csv.reader(f)
for i in ro:
print(i)
def search():
f=open("details.csv","r")
found=0
u=input("enter userId to search:")
ro=csv.reader(f)

11 | P a g e
next(ro)
for i in ro:
if i[0]==u:
print(i[1])
found=1
f.close
if found==0:
print("sorry not found")
write()
read()
search()

12 | P a g e
PRACTICAL 7
Python program to create a binary file with roll no. and name search for a given roll no.
and display name.
Ans):-
import pickle
# Function to create and write to a binary file
def create_binary_file(filename):
# Open the file in write-binary mode
with open(filename, 'wb') as file:
students = []
while True:
roll_no = input("Enter roll number (or 'exit' to stop): ")
if roll_no.lower() == 'exit':
break
name = input("Enter student name: ")
students.append((roll_no, name)) # Add the (roll_no, name) tuple to the list
# Serialize the list of students and write to the binary file
pickle.dump(students, file)
print("Student data has been written to the binary file.")
# Function to search for a given roll number and display the name
def search_roll_no(filename, roll_no):
try:
# Open the file in read-binary mode
with open(filename, 'rb') as file:
students = pickle.load(file) # Deserialize the data (list of students)
# Search for the roll number

13 | P a g e
for student in students:
if student[0] == roll_no:
return student[1] # Return the name if roll number matches
return None # Return None if roll number is not found
except FileNotFoundError:
print("Error: The binary file does not exist.")
return None
# Main function to manage the flow of the program
def main():
filename = "students_data.bin"
# Create and write to the binary file
create_binary_file(filename)
# Search for a roll number
search_roll = input("Enter roll number to search for the name: ")
name = search_roll_no(filename, search_roll)
if name:
print(f"The name associated with roll number {search_roll} is: {name}")
else:
print(f"Roll number {search_roll} not found.")
# Run the program
if __name__ == "__main__":
main()

14 | P a g e
PRACTICAL 8
Python program to count and display no.of vowels consonants uppercase and
lower case characters.
Ans):-def count_characters(text):
vowels = "aeiouAEIOU"
vowels_count = 0
consonants_count = 0
uppercase_count = 0
lowercase_count = 0
# Loop through each character in the text
for char in text:
if char.isalpha(): # Check if the character is an alphabet letter
if char in vowels:
vowels_count += 1
else:
consonants_count += 1
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
# Display the results
print(f"Vowels: {vowels_count}")
print(f"Consonants: {consonants_count}")
print(f"Uppercase letters: {uppercase_count}")
print(f"Lowercase letters: {lowercase_count}")
# Input text from the user
input_text = input("Enter a string: ")
# Call the function to count and display the results
count_characters(input_text)

15 | P a g e
PRACTICAL 9
Create a student table and insert data implement the following SQL commands on the
student table: ALTER table to add new attributes/modify data type/drop attribute
UPDATE table to modify data ORDER By to display data in ascending/descending order
DELETE to remove tuple(s) GROUP BY and find the min, max ,sum , count and average.
Ans):-
-- 1. Create the table and insert data
CREATE TABLE student (
student_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
age INT,
grade CHAR(1),
gpa DECIMAL(3, 2)
);
INSERT INTO student (student_id, first_name, last_name, age, grade, gpa) VALUES
(1, 'John', 'Doe', 20, 'A', 3.85),
(2, 'Jane', 'Smith', 22, 'B', 3.50),
(3, 'Alice', 'Johnson', 21, 'A', 3.95),
(4, 'Bob', 'Brown', 23, 'C', 2.75),
(5, 'Charlie', 'Davis', 20, 'B', 3.60);

-- 2. Alter the table to add, modify, and drop columns


16 | P a g e
ALTER TABLE student
ADD phone_number VARCHAR(15);

ALTER TABLE student


MODIFY gpa DECIMAL(4, 3);

ALTER TABLE student


DROP COLUMN phone_number;

-- 3. Update records
UPDATE student
SET grade = 'B'
WHERE student_id = 4;

17 | P a g e
UPDATE student
SET gpa = gpa + 0.2
WHERE gpa < 3.0;

-- 4. ORDER BY to sort data


SELECT * FROM student
ORDER BY gpa ASC;

SELECT * FROM student


18 | P a g e
ORDER BY gpa DESC;

-- 5. Delete records
DELETE FROM student
WHERE student_id = 4;

DELETE FROM student


WHERE gpa < 3.0;
(same output as above)
-- 6. Aggregate functions and GROUP BY
SELECT MIN(gpa) AS min_gpa FROM student;

SELECT MAX(gpa) AS max_gpa FROM student;

19 | P a g e
SELECT SUM(gpa) AS total_gpa FROM student;

SELECT grade, COUNT(*) AS student_count


FROM student
GROUP BY grade;

SELECT AVG(gpa) AS average_gpa FROM student;

20 | P a g e
PRACTICAL 10
Read a csv file top 5 csv and print them with top defumiter ignore first row header to
print in tabular form.
Ans):-
import csv
# Function to read and display top 5 rows from the CSV file
def read_csv_top_5(filename):
with open(filename, mode='r') as file:
csv_reader = csv.reader(file)
header = next(csv_reader) # Skip the header row
print("Displaying top 5 rows (excluding header):")
# Print the header (column names)
print("\t".join(header))
# Read and print the next 5 rows
count = 0
for row in csv_reader:
if count == 5:
break
print("\t".join(row))
count += 1
# Example usage
filename = 'your_file.csv' # Replace with your CSV file path
read_csv_top_5(filename)

21 | P a g e
PRACTICAL 11
Create a text file intro.txt in python and ask the user to write a single link text by user
input.
Ans):-
# Ask the user to input a single line of text
user_input = input("Please enter a line of text to be written to 'intro.txt': ")
# Open the file in write mode (this will create the file if it doesn't exist)
with open('intro.txt', 'w') as file:
# Write the user's input to the file
file.write(user_input)
# Inform the user that the text has been written
print("Your text has been written to 'intro.txt'.")

22 | P a g e
PRACTICAL 12
Write a program to count a to that no of times starting with a ,b, and c form the file
myfile.txt.
Ans):-
def count_words_starting_with_letters(filename):
# Initialize counters for words starting with 'a', 'b', and 'c'
count_a = 0
count_b = 0
count_c = 0
try:
# Open the file in read mode
with open(filename, 'r') as file:
# Read all the content from the file
content = file.read()
# Split the content into words (assuming space as the delimiter)
words = content.split()
# Iterate through each word and check the first character
for word in words:
# Convert to lowercase to make the check case-insensitive
first_char = word[0].lower()
if first_char == 'a':
count_a += 1
elif first_char == 'b':
count_b += 1
elif first_char == 'c':
count_c += 1
# Print the counts for words starting with 'a', 'b', and 'c'
print(f"Words starting with 'a': {count_a}")
print(f"Words starting with 'b': {count_b}")

23 | P a g e
print(f"Words starting with 'c': {count_c}")

except FileNotFoundError:
print("Error: The file does not exist.")
# Call the function with the filename 'myfile.txt'
filename = 'myfile.txt'
count_words_starting_with_letters(filename)

24 | P a g e
Practical-13
Write a python program to demonstrate the concept of variable length argument
to calculate product and power of the first 10 numbers.
Ans):-
# Function to calculate the product of the arguments
def calculate_product(*args):
product = 1
for num in args:
product *= num
return product
# Function to calculate the power of the first 10 numbers
def calculate_power(*args):
powers = []
for num in args:
powers.append(num ** 2) # Calculating square as power (num^2) of each
number
return powers
# First 10 numbers
numbers = list(range(1, 11))
# Calculate product of the first 10 numbers
product_result = calculate_product(*numbers)
# Calculate the power (square) of the first 10 numbers
power_result = calculate_power(*numbers)
# Display results
print(f"The product of the first 10 numbers is: {product_result}")
print(f"The power (square) of the first 10 numbers is: {power_result}")

25 | P a g e
Practical-14
Modify the program and display customer details based on the following menu:
(i)city (ii)name (iii)bill amount (iv) category
Ans):-
# Sample customer data
customers = [
{"city": "New Delhi", "name": "John Doe", "bill_amount": 1500, "category":
"Gold"},
{"city": "Mumbai", "name": "Jane Smith", "bill_amount": 2000, "category":
"Silver"},
{"city": "Bangalore", "name": "Alice Johnson", "bill_amount": 2500, "category":
"Platinum"}
]
def display_customer_details(option):
if option == 'i':
for customer in customers:
print(f"City: {customer['city']}")
elif option == 'ii':
for customer in customers:
print(f"Name: {customer['name']}")
elif option == 'iii':
for customer in customers:
print(f"Bill Amount: {customer['bill_amount']}")
elif option == 'iv':
for customer in customers:
print(f"Category: {customer['category']}")
else:
print("Invalid option! Please choose a valid option from the menu.")
# Display menu
print("Choose an option to display customer details:")

26 | P a g e
print("(i) City")
print("(ii) Name")
print("(iii) Bill Amount")
print("(iv) Category")
# Get user's choice
user_choice = input("Enter your choice: ").lower()
# Display customer details based on user's choice
display_customer_details(user_choice)

27 | P a g e
Practical-15
Create a binary file client.dat to hold records like client ID, client name and address
using the dictionary write functions to write data, read them and print on the
screen.
Ans):-
import pickle
# Function to write client data to a binary file
def write_client_data(filename):
# Dictionary to hold client records
clients = [
{"client_id": 1, "client_name": "Alice", "address": "123 Elm Street"},
{"client_id": 2, "client_name": "Bob", "address": "456 Oak Avenue"},
{"client_id": 3, "client_name": "Charlie", "address": "789 Pine Road"}
]
# Open the binary file in write mode
with open(filename, 'wb') as file:
# Use pickle to serialize the clients dictionary and write it to the file
pickle.dump(clients, file)
print("Client data has been written to", filename)
# Function to read client data from a binary file and print it
def read_client_data(filename):
try:
# Open the binary file in read mode
with open(filename, 'rb') as file:
# Use pickle to deserialize the data
clients = pickle.load(file)
# Print the client records
print("\nClient Records from", filename)

28 | P a g e
for client in clients:
print(f"Client ID: {client['client_id']}, Name: {client['client_name']}, Address:
{client['address']}")
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
# Main program execution
filename = 'client.dat'
# Write client data to the binary file
write_client_data(filename)
# Read and print the client data from the binary file
read_client_data(filename)

29 | P a g e

You might also like