0% found this document useful (0 votes)
15 views8 pages

Cs Practical

Uploaded by

mm718982
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

Cs Practical

Uploaded by

mm718982
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

1)def wordseperated():

f=open("ninja.txt","r")

lines=f.readlines()

print(lines)

for line in lines:

word=line.split()

for x in word:

print(x+"#",end=' ')

wordseperated()

2)stack=[]

def push():

element=input("Enter the element:")

stack.append(element)

print(stack)

def pop_element():

if not stack:

print("Stack is empty!")

else:

e=stack.pop()

print("removed element:",e)

print(stack)

while True:

print("select the operation 1.push 2.pop 3.quit")

choice=int(input("Enter your choice"))

if choice==1:

push()

elif choice==2:

pop_element()

elif choice==3:

break

else:

print("Enter the correct operation!")


3)import pickle

stu={}

stufile=open("stu.dat","wb")

ans="y"

while ans=="y":

rno=int(input("enter roll number"))

name=input("enter name")

stu["rollno"]=rno

stu["name"]=name

pickle.dump(stu,stufile)

ans=input("want to enter more record?(y/n)...")

stufile.close()

found=False

srch=open("stu.dat","rb")

search=int(input("enter the roll number to be searched for:"))

try:

while True:

stu=pickle.load(srch)

if stu["rollno"]==search:

print(stu)

found=True

except EOFError:

if found==False:

print("no such records found in file")

else:

print("search successful")

srch.close()

4) import csv

def get_item_details():

items = []

print("Enter item details. Type 'done' to finish.")

while True:

code = input("Enter item code (or type 'done' to stop): ")

if code.lower() == 'done':
break

description = input("Enter item description: ")

price = input("Enter item price: ")

try:

price = float(price)

except ValueError:

print("Invalid price. Please enter a numeric value.")

continue

items.append([code, description, price])

return items

def write_to_csv(filename, items):

with open(filename, mode='w', newline='', encoding='utf-8') as file:

writer = csv.writer(file)

writer.writerow(["Code", "Description", "Price"])

writer.writerows(items)

print(f"Item details have been saved to '{filename}'")

def main():

filename = "items.csv"

items = get_item_details()

if items:

write_to_csv(filename, items)

else:

print("No items to write.")

if __name__ == "__main__":

main()

5)def counts():

f=open("poem.txt","r")

v=c=u=l=0

data=f.read()
for i in data:

if i.isalpha():

if i.isupper():

u+=1

if i.islower():

l+=1

if i.upper() and i.lower() in 'AEIOUaeiou':

v+=1

else:

c+=1

print("vowerls=",v)

print("consonants=",c)

print("uppercase=", u)

print("lowercase=", l)

counts()

6) import pickle

# Function to write records into the binary file

def WRITE():

with open("EMPLOYEE.dat", "wb") as file: # Open the file in write-binary mode

n = int(input("Enter the number of records to add: "))

for _ in range(n):

EMPID = int(input("Enter Employee ID: "))

EMPNAME = input("Enter Employee Name: ")

SALARY = float(input("Enter Salary: "))

record = [EMPID, EMPNAME, SALARY]

pickle.dump(record, file) # Store the record in the file

print(f"{n} record(s) added successfully.")

# Function to read and display all records from the binary file

def READ():

try:

with open("EMPLOYEE.dat", "rb") as file: # Open the file in read-binary mode

print("\nEmployee Records:")

while True:
try:

record = pickle.load(file) # Load the record

print(f"EMPID: {record[0]}, EMPNAME: {record[1]}, SALARY: {record[2]}")

except EOFError:

break # End of file reached

except FileNotFoundError:

print("No records found. Please write data first.")

# Main program

while True:

print("\nMenu:")

print("1. Write records")

print("2. Read records")

print("3. Exit")

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

if choice == '1':

WRITE()

elif choice == '2':

READ()

elif choice == '3':

print("Exiting the program. Goodbye!")

break

else:

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

7) import csv

# Function to write records into the CSV file

def WRITE():

with open("product.csv", "w", newline="") as file: # Open the file in write mode

writer = csv.writer(file)

writer.writerow(["PID", "PNAME", "PRICE"]) # Write the header row

n = int(input("Enter the number of records to add: "))

for _ in range(n):

PID = input("Enter Product ID: ")


PNAME = input("Enter Product Name: ")

PRICE = float(input("Enter Product Price: "))

writer.writerow([PID, PNAME, PRICE]) # Write the record

print(f"{n} record(s) added successfully.")

# Function to read and display all records from the CSV file

def READ():

try:

with open("product.csv", "r") as file: # Open the file in read mode

reader = csv.reader(file)

print("\nProduct Records:")

for row in reader:

print(", ".join(row)) # Display each row

except FileNotFoundError:

print("No records found. Please write data first.")

# Main program

while True:

print("\nMenu:")

print("1. Write records")

print("2. Read records")

print("3. Exit")

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

if choice == '1':

WRITE()

elif choice == '2':

READ()

elif choice == '3':

print("Exiting the program. Goodbye!")

break

else:

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

8) def POP(stack):

if not stack:
print("The stack is empty.")

else:

print("\nPopping elements from the stack (LIFO order):")

while stack:

print(stack.pop()) # Pop and display the top element

# Main program

stack = [] # Initialize an empty stack

while True:

print("\nMenu:")

print("1. Push records into the stack")

print("2. Pop and display stack content")

print("3. Exit")

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

if choice == '1':

PUSH(stack)

elif choice == '2':

POP(stack)

elif choice == '3':

print("Exiting the program. Goodbye!")

break

else:

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

9) def PUSH(stack):

n = int(input("Enter the number of integers in the tuple: "))

values = []

for _ in range(n):

value = int(input("Enter an integer: "))

values.append(value)

data_tuple = tuple(values) # Create a tuple of integers

for item in data_tuple:

if item % 2 == 0: # Check if the number is even

stack.append(item) # Push even number into the stack


print(str(item) + " added to the stack.")

if not stack:

print("No even numbers found to push into the stack.")

# Function to pop and display stack content in LIFO order

def POP(stack):

if not stack:

print("The stack is empty.")

else:

print("\nPopping elements from the stack (LIFO order):")

while stack:

print(stack.pop()) # Pop and display the top element

# Main program

stack = [] # Initialize an empty stack

while True:

print("\nMenu:")

print("1. Push even integers into the stack")

print("2. Pop and display stack content")

print("3. Exit")

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

if choice == '1':

PUSH(stack)

elif choice == '2':

POP(stack)

elif choice == '3':

print("Exiting the program. Goodbye!")

break

else:

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

You might also like