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

Computer Science Practical File

The document outlines a series of practical exercises in Python focusing on file handling, data structures, and basic programming concepts. It includes tasks such as creating and manipulating text files, using pickle for binary file operations, implementing stacks and queues, and building a simple calculator. Each practical exercise is accompanied by its aim, code implementation, and expected output.

Uploaded by

shivanshrawat628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Computer Science Practical File

The document outlines a series of practical exercises in Python focusing on file handling, data structures, and basic programming concepts. It includes tasks such as creating and manipulating text files, using pickle for binary file operations, implementing stacks and queues, and building a simple calculator. Each practical exercise is accompanied by its aim, code implementation, and expected output.

Uploaded by

shivanshrawat628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Computer Science Practical File

S.NO.
AIM
1 A text file “intro.txt” in python and asked the user to
write a single line of text by user input
2 To create a text file “MyFile.txt” in python and ask
the user to write separate 3 lines with three input
statements from the user.

3 To read the contents of both the files created in the


above programs and merge the contents into
“merge.txt”.
4 To Count the total number of upper case, lower case,
and digits used in the text file “merge.txt”.

5 To Create a sample dictionary in pickle using dump


and load
6 To create a binary file which contains student roll
number and data using pickle.
7 To search the data of the student you want with the
help of roll number in a binary file using pickle.

8 To update the binary file

9 To Write in csv File

10 To read in CSV file

11 To push Elements into stack.

12 To push and pop the elements from the stack

13 To push, pop, and display the element by taking the


input from the user.

14 To make a simple calculator

15 To create a csv file which contains the info of buses


and no. of students it can carry and using updating
and searching.
16 To implement queue in python using list.

17
18
19
20

Practical 1:

Aim: A text file “intro.txt” in python and asked the user to write a
single line of text by user input.

Code:
def program1():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close()
program1()

Output:
Practical 2:

Aim: To create a text file “MyFile.txt” in python and ask the user to
write separate 3 lines with three input statements from the user.

Code:
def program2():
f = open("MyFile.txt","w")
line1=input("Enter the text:")
line2=input("Enter the text:")
line3=input("Enter the text:")
new_line="\n"
f.write(line1)
f.write(new_line)
f.write(line2)
f.write(new_line)
f.write(line3)
f.write(new_line)
f.close()
program2()

Output:
Practical 3:

Aim: To read the contents of both the files created in the above
programs and merge the contents into “merge.txt”.

Code:
def program3():
with open("MyFile.txt","r") as f1:
data=f1.read()
with open("intro.txt","r") as f2:
data1=f2.read()
with open("merge.txt","w") as f3:
f3.write(data)
f3.write(data1)
program3()

Output:
Practical 4:

Aim: To Count the total number of upper case, lower case, and digits
used in the text file “merge.txt”.

Code:
def program4():
with open("merge.txt","r") as f1:
data=f1.read()
cnt_ucase =0
cnt_lcase=0
cnt_digits=0
for ch in data:
if ch.islower():
cnt_lcase+=1
if ch.isupper():
cnt_ucase+=1
if ch.isdigit():
cnt_digits+=1
print("Total Number of Upper Case letters are:",cnt_ucase)
print("Total Number of Lower Case letters are:",cnt_lcase)
print("Total Number of digits are:",cnt_digits)
program4()

Output:
Practical 5:

Aim: To Create a sample dictionary in pickle using dump and load

Code:
import pickle
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.pickle', 'wb') as file:
pickle.dump(data, file)
with open('data.pickle', 'rb') as file:
loaded_data = pickle.load(file)
print("Loaded data:", loaded_data)

Output:
Practical 6:

Aim: To create a binary file which contains student roll number


and data using pickle.

Code:
import pickle
def w_binary():
p=open("today.dat","wb")
k="y"
while k=="y":
roll=input("Enter your roll no.: ")
name=input("Enter you name: ")
data=[roll,name]
pickle.dump(data,p)
k=input("Another Record y/n?: ")
p.close()
def r_binary():
p=open("today.dat","rb")
while True:
try:
k=pickle.load(p)
print(k)
except:
p.close()
w_binary()
r_binary()

Output:
Practical 7:

Aim: To search the data of the student you want with the help of
roll number in a binary file using pickle.

Code:
import pickle
def w_binary():
p=open("today.dat","ab")
k="y"
while k=="y":
roll=input("Enter your roll no.: ")
name=input("Enter you name: ")
data=[roll,name]
pickle.dump(data,p)
k=input("Another Record y/n?: ")
p.close()
def r_binary():
p=open("today.dat","rb")
while True:
try:
k=pickle.load(p)
print(k)
except:
p.close()
def s_binary():
p=open("today.dat","rb")
r=input("Which roll no. data you want: ")
find=0
while True:
try:
k=pickle.load(p)
if k[0]==r:
print(k)
find=1
break
except:
p.close()
break
if find==0:
print("Not Found")

w_binary()
#r_binary()
s_binary()

Output:

Practical 8:
Aim: To update the binary file

Code:
import pickle
def w_binary():
p=open("today.dat","ab")
k="y"
while k=="y":
roll=input("Enter your roll no.: ")
name=input("Enter you name: ")
data=[roll,name]
pickle.dump(data,p)
k=input("Another Record y/n?: ")
p.close()
def r_binary():
p=open("today.dat","rb")
while True:
try:
k=pickle.load(p)
print(k)
except:
p.close()
def u_binary():
p=open("today.dat","rb+")
r=input("Enter the data you want to update: ")
while True:
try:
location=p.tell()
k=pickle.load(p)
if k[0]==r:
p.seek(location,0)
roll=input("Enter the roll no.: ")
name=input("Enter your name: ")
data=[roll,name]
pickle.dump(data,p)
p.close
break
except:
p.close()
break

w_binary()
#r_binary()
u_binary()
r_binary()

Output

Practical 9:
Aim: To Write in csv File

Code:
import csv
p=open("laptop.csv","w",newline="")
w=csv.writer(p)
h=["Rollno","Name","Marks"]
w.writerow(h)
data=[[1,"Karan",97],[2,"Pooja",91],[3,"Deepak",68]]
w.writerows(data)
p.close

Output:
Practical 10:

Aim: To read in CSV file


Code:

import csv
p=open("laptop.csv","w",newline="")
w=csv.writer(p)
h=["Rollno","Name","Marks"]
w.writerow(h)
data=[[1,"Karan",97],[2,"Pooja",91],[3,"Deepak",68]]
w.writerows(data)
p.close()

p=open("laptop.csv","r")
r=csv.reader(p)
for x in r:
print(x)
p.close()

Output:
Practical 11

Aim: To push Elements into stack.

Code:

stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print("Stack after pushing elements:", stack)

Output:

Practical 12:

Aim: To push and pop the elements from the stack

Code:
stack = []

stack.append(1)
stack.append(2)
stack.append(3)

print("Stack after pushing elements:", stack)

if stack:
popped_element = stack.pop()
print("Popped element:", popped_element)
else:
print("Stack is empty.")

print("Stack after popping:", stack)

Output:

Practical 13:

Aim: To push, pop, and display the element by taking


the input from the user.

Code:
stack = []
while True:
print("\nOptions:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Quit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '1':
item = input("Enter the element to push: ")
stack.append(item)
print(f"{item} pushed onto the stack.")
elif choice == '2':
if stack:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")
else:
print("Stack is empty.")
elif choice == '3':
print("Stack:", stack)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please choose 1, 2, 3, or 4.")

Output:
Practical 14:

Aim: To Create a simple calculator

Code:
def add(x, y):

return x + y

def subtract(x, y):

return x - y

def multiply(x, y):

return x * y
def divide(x, y):

if y == 0:

return "Cannot divide by zero"

return x / y

while True:

print("\nOptions:")

print("1. Add")

print("2. Subtract")

print("3. Multiply")

print("4. Divide")

print("5. Quit")

choice = input("Enter your choice (1/2/3/4/5): ")

if choice == '5':

print("Exiting the calculator.")

break

if choice in ('1', '2', '3', '4'):

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

if choice == '1':

print("Result:", add(num1, num2))

elif choice == '2':

print("Result:", subtract(num1, num2))

elif choice == '3':

print("Result:", multiply(num1, num2))

elif choice == '4':

result = divide(num1, num2)

if isinstance(result, str):
print(result)

else:

print("Result:", result)

else:

print("Invalid choice. Please choose 1, 2, 3, 4, or 5.")

Output:
Practical 15:

Aim: To create a csv file which contains the info of buses and no.
of students it can carry and using updating and searching.

Code:
import csv

def create_or_load_csv(file_name):

try:

with open(file_name, mode='r') as file:

return list(csv.DictReader(file))

except FileNotFoundError:

print(f"File '{file_name}' not found. Creating a new file.")

return []

def save_to_csv(file_name, data):

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

fieldnames = data[0].keys() if data else []

writer = csv.DictWriter(file, fieldnames=fieldnames)

writer.writeheader()
writer.writerows(data)

def update_bus_info(data, bus_number, capacity):

for row in data:

if row['Bus Number'] == bus_number:

row['Capacity'] = capacity

return True

return False

def search_bus_info(data, bus_number):

for row in data:

if row['Bus Number'] == bus_number:

return row

return None

csv_file = 'bus_info.csv'

bus_data = create_or_load_csv(csv_file)

while True:

print("\nOptions:")

print("1. Add/Update Bus Information")

print("2. Search Bus Information")

print("3. Display All Bus Information")

print("4. Quit")

choice = input("Enter your choice (1/2/3/4): ")

if choice == '4':

save_to_csv(csv_file, bus_data)

print("Exiting the program.")

break

if choice == '1':

bus_number = input("Enter Bus Number: ")

capacity = input("Enter Capacity (students it can carry): ")

if update_bus_info(bus_data, bus_number, capacity):

print(f"Bus {bus_number} information updated.")

else:
bus_data.append({'Bus Number': bus_number, 'Capacity': capacity})

print(f"Bus {bus_number} information added.")

elif choice == '2':

bus_number = input("Enter Bus Number to search: ")

bus_info = search_bus_info(bus_data, bus_number)

if bus_info:

print("Bus Number:", bus_info['Bus Number'])

print("Capacity:", bus_info['Capacity'])

else:

print(f"Bus {bus_number} not found.")

elif choice == '3':

if bus_data:

print("\nAll Bus Information:")

for row in bus_data:

print("Bus Number:", row['Bus Number'])

print("Capacity:", row['Capacity'])

else:

print("No bus information available.")

else:

print("Invalid choice. Please choose 1, 2, 3, or 4.")

Output:
Practical 16:

Aim: To implement queue in python using list.

Code:
queue = []

while True:

print("\nOptions:")

print("1. Enqueue (Add to Queue)")

print("2. Dequeue (Remove from Queue)")

print("3. Display Queue")

print("4. Quit")
choice = input("Enter your choice (1/2/3/4): ")

if choice == '4':

print("Exiting the program.")

break

if choice == '1':

item = input("Enter the element to enqueue: ")

queue.append(item)

print(f"{item} enqueued.")

elif choice == '2':

if queue:

dequeued_item = queue.pop(0)

print(f"Dequeued item: {dequeued_item}")

else:

print("Queue is empty.")

elif choice == '3':

if queue:

print("Queue:", queue)

else:

print("Queue is empty.")

else:

print("Invalid choice. Please choose 1, 2, 3, or 4.")

Output:
Practical 17:

Aim:

Code:

Output:

You might also like