Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Pramit CS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Name : Pramit

Class : XII ‘A’

Roll NO : 1224

Subject: Computer Science Practical File

Submitted To : Mrs. Leena Kaushik Ma’am


PACTICAL NAME

1. Write a python program to print the following pattern.

2. Write a program to generate prime numbers up to N. Where N is a user input more than
3. A wrong input should display proper error message.

3.
Write a python program to count the number of characters (character frequency) in a
string.

4. Write a python program to count and display the vowels of a given text.

5. Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.

6.
Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.

7. Write a python program to capitalize first and last letters of each word of a given string.

8. WAP for bubble sort.

9. WAP for insertion sort

10 RAHU AND ARYAN BOTH ARE FRIEND THEY WAHT TO DISPLAY ADDITION OF
AGE SUBTRACTION OF FIGHTS MUPLTIPLIER AND DIVISION OF IQ.
DESCRIPTION AS FOLLOWS:

11. Write definition of a method ZeroEnding(scores) to add all those values in the list of
scores, which are ending with zero(0) and display the sum.

12.
Write a user – defined function which take string as a parameter and check whether the
string contains digit or not if it contains digit then calculate the sum of digits and print the
digit and print the original string. If it is not contained digit then it give original string with
appropriate message, “No digit is present “.

13. WAP to read first 20 bytes and print them.

14. WAF to read the contents from a ‘abc.txt’ line by line and display the same on the
screen.
15.
WAF inn python to read lines from a text file abc.txt and display those lines which are
starting with alphabet’F’.

16. WAF to count how many lines are start with ‘f’.

17. WAF to read abc.txt and print those lines which are start with alphabet ‘f’ or ‘d’ including
both case.
Write a method in python to read lines from a file abc.txt and display those lines which
18.
are bigger than 50 characters.
WAF to count no. of characters from a file.

19.

20. WAF to count the total no. of words in a file.

21. WAF to read lines from a text file to find and display the occourance of the word ‘and’.

22. WAF to read thr contents from a text file and display the occurance of those words
which are having five or more alphabets.
WAF to read contents of a file to count and display the occurance of the words ‘is’ , ‘up’
23.
, ‘to’.

24. WAF to write data to the text file.

25. WAP to write student details in abc.txt.

26. WAP to write details of 30 students in student.txt.

27. WAP to read data from student.dat.

28. WAP to a binary file called emp.dat and write into it employee details of some
employees available in the form of dictionary.
Write a menu driven code to perform all binary operations on binary file.
29.

1
-

Q-1 Write a python program to print the following pattern.


13
6 2
10 5 4
9 8 7

SOLUTION:
def print_pattern(rows):

num = 1
for i in range(1, rows + 1):

for j in range(i, 0, -1):


print(num, end="\t")
num += 1

print()
rows = 4
print_pattern(rows)

OUTPUT-
-

Q-2 Write a program to generate prime numbers up to N. Where N is a user input more
than 3. A wrong input should display proper error message.
SOLUTION:

def is_prime(num):

if num < 2:
return False

for i in range(2, int(num**0.5) + 1):


if num % i == 0:

return False
return True

try:

N = int(input("Enter a number greater than 3: "))


if N <= 3:

print("Please enter a valid number greater than 3.")

else:

print("Prime numbers up to", N, "are:")


for num in range(2, N + 1):

if is_prime(num):

print(num)

except ValueError:

print("Invalid input. Please enter a valid integer greater than 3.")

OUTPUT-
-

Q-3 Write a python program to count the number of characters (character


frequency) in a string.
SOLUTION:
def char_frequency(test_str):

result = {}
for char in test_str:
result[char] = result.get(char, 0) + 1

return result
input_str = "vivekmaurya"
result = char_frequency(input_str)
print("Character frequencies in vivekmaurya:")
print(result)
OUTPUT-
Q-4 Write a python program to count and display the vowels of a given text.
SOLUTION:
def count_vowels_method(text):

vowels = "aeiouAEIOU"

return sum(text.lower().count(vowel) for vowel in vowels)

input_text = input("Enter a text: ")

num_vowels_method = count_vowels_method(input_text)

print("Total number of vowels using count() method: ",num_vowels_method)

OUTPUT :
Q-5 Write a python program to swap each character of a given string from
lowercase to uppercase and vice versa.
SOLUTION:

def swap_case(text):

return text.swapcase()

input_text = input("Enter a string: ")

swapped_text = swap_case(input_text)

print("Swapped text:", swapped_text)

OUTPUT:
-

Q-6 Write a python program to swap each character of a given string from lowercase to
uppercase and vice versa.
SOLUTION:
def find_longest_word(word_list):

longest_word = max(word_list, key=len)


return len(longest_word)
# Example usage:
words = ["apple", "banana", "grapefruit", "kiwi"]
longest_length = find_longest_word(words)
print(f"Length of the longest word: {longest_length}")

OUTPUT:
-

Q-7 Write a python program to capitalize first and last letters of each word of a given
string.
SOLUTION:

def capitalize_words(s):

words = s.split()

result = []

for word in words:

modified_word
=word[0].upper()+word[1:-1] + word[-
1].upper()

result.append(modified_word)

return ' '.join(result)

input_str = "welcome to fds"

print("String before:", input_str)

print("String after:",
capitalize_words(input_str))

OUTPUT:
-

Q-8 WAP for bubble sort.

SOLUTION:
def bubble_sort(arr):

n = len(arr)
for i in range(n):

for j in range(0, n -i - 1):


if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]

# Example usage:
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)

OUTPUT:
-

Q-9 WAP for insertion sort


SOLUTION:
def insertion_sort(arr):

for i in range(1, len(arr)):

key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:

arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

# Example usage:
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print("Sorted array is:", arr)

OUTPUT:
-

Q-10 RAHU AND ARYAN BOTH ARE FRIEND THEY WAHT TO DISPLAY ADDITION
OF AGE SUBTRACTION OF FIGHTS MUPLTIPLIER AND DIVISION OF IQ.
DESCRIPTION AS FOLLOWS:

RAHUL DESCRIPTION
AGE 32
HEIGHT 175 cm
WEIGHT 75 kg
IQ 100

ARYAN DESCRIPTION
AGE 25
HEIGHT 165 cm
WEIGHT 75 kg

IQ 50
FIRSTLY, DEFINE THE FUNCTION add(), mul (), & div()
SOLUTION:
def add(a, b):

return a + b
def sub(a, b):

return a - b
def mul(a, b):

return a * b
def div(a, b):
if b != 0:

return a / b

else:
return "Cannot divide by zero!"
-

# Example usage:
rahul_age = 32
aryan_age = 25

rahul_weight = 75
aryan_weight = 75
rahul_iq = 100
aryan_iq = 50
print("Addition of ages:", add(rahul_age, aryan_age))
print("Subtraction of fights (assuming zero):", sub(rahul_age, aryan_age))
print("Multiplication of weights:", mul(rahul_weight, aryan_weight))
print("Division of IQs:", div(rahul_iq, aryan_iq))

OUTPUT:
-

Q-11 Write definition of a method ZeroEnding(scores) to add all those values in the list of
scores, which are ending with zero(0) and display the sum.
For example,

If the scores contain [200, 456,300,100,234,678]


The sum should e displayed as 600

SOLUTION:
def ZeroEnding(scores):
total = 0
for number in scores:
if number % 10 == 0:
total += number
return total

# Example usage:
scores = [200, 456, 300, 100, 234, 678]
result = ZeroEnding(scores)
print("Sum of values ending with zero:", result)

OUTPUT:
Q-12 Write a user – defined function which take string as a parameter and check whether
the string contains digit or not if it contains digit then calculate the sum of digits and print
the digit and print the original string. If it is not contained digit then it give original string
with appropriate message, “No digit is present “.

SOLUTION:
def process_string(input_string):

has_digit = any(char.isdigit() for char in input_string)

if has_digit:

digit_sum = sum(int(char) for char in

input_string ifchar.isdigit())

print(f"Original string: {input_string}")


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

else:

print(f"Original string: {input_string}")


print("No digit is present.")

# Example usage:
user_input = input("Enter a string: ")

process_string(user_input)
OUTPUT:
Q -13 WAP to read first 20 bytes and print them.

SOLUTION:
a=open(“abc.txt”,’r’)
Data = a.read(20)

print(Data)

a.close()

OUTPUT:
Q- 14 WAF to read the contents from a ‘abc.txt’ line by line and display the same on the screen.

SOLUTION: def

read():

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

data = f.readlines() for

i in data: if data == '':

break else:

print(i,end='')
f.close() read()

OUTPUT:

FILE:
Q-15 WAF inn python to read lines from a text file abc.txt and display those lines which are
starting with alphabet’F’.
SOLUTION: def
abc():

f=open('abc.txt','r')

data = f.readlines()
for i in data: if

i[0]=='f': print(i)

f.close() abc()
OUTPUT:

FILE:
Q-16 WAF to count how many lines are start with ‘f’.
SOLUTION: def abc(): with
open("abc.txt", "r") as f:

data = f.readlines() a=0 for i in


data: if i[0] == "f": a += 1

print("total lines start with f are", a)


abc()

OUTPUT:

FILE:
Q-17 WAF to read abc.txt and print those lines which are start with alphabet ‘f’ or ‘d’
including both case.
SOLUTION: def abc():
with open('abc.txt') as f:

a = f.readlines() for i
in a: if i[0] == 'f' or

i[0]== 'd':

print(i)

abc()

OUTPUT:

FILE:
Q-18 Write a method in python to read lines from a file abc.txt and display those lines
which are bigger than 50 characters.
SOLUTION: def abc(): with
open("abc.txt") as f:

a = f.readlines()
for i in a: if
len(i) >= 50:

print(i) else:
print("not exist!")
abc() OUTPUT:

FILE:
Q-19WAF to count no. of characters from a file.
SOLUTION: def abc(): with
open("abc.txt") as f:

n = f.read()
c=0 for i in
n: if
i.isalpha():

c += 1 print("total

characters:",c) abc()

OUTPUT:

FILE:
Q-20 WAF to count the total no. of words in a file.
SOLUTION: def abc(): with
open("abc.txt") as a:

b = a.read() c = b.split()

print("total words:", len(c))


abc()
OUTPUT:

FILE:
Q-21 WAF to read lines from a text file to find and display the occourance of the word
‘and’.
SOLUTION: def abc(): with
open("abc.txt") as a:

b = a.read() c = b.split()
d=0 for i in c: if i ==

'and' or i == 'And':

d += 1 print("The number of 'and' in the


file is: ", d) abc()
OUTPUT:

FILE:

Q 22 WAF to read thr contents from a text file and display the occurance of those words
which are having five or more alphabets.
SOLUTIONS: def abc():
with open("abc.txt") as z:

f = z.read()
h = f.split() a

=0 for i in h:

if len(i) >= 5:
a += 1

print("There are", a, "words with 5 or more letters.") abc()

OUTPUT:

FILE:
Q-23 WAF to read contents of a file to count and display the occurance of the words ‘is’ ,
‘up’ , ‘to’.
SOLUTION: def abc(): with
open("abc.txt") as z:

f = z.read() h=
f.split() a=0 for
i in h: if i in
['is','up','to']:

a += 1 print("Total words are present in


the file:",a) abc() OUTPUT:

FILE:
Q-24 WAF to write data to the text file.
SOLUTION: with
open("sample.txt", "w") as f:
f.write("Hello World")

f.write("This is our new text file \n") with

open(r"sample.txt", "r") as f:

a = f.read()

print(a)

OUTPUT:

NEW FILE IS CREATED:


Q-25 WAP to write student details in abc.txt.
SOLUTION:

import pickle with

open("abc.txt", "wb") as a:

std = {} std['name'] = 'xyz'


std['age'] = '18' std['class'] =
'XII' pickle.dump(std, a) with
open("abc.txt", "rb") as a:

std = pickle.load(a) print(std)


OUTPUT:
Q-26 WAP to write details of 30 students in student.txt.
SOLUTION:
import pickle with
open("abc.txt", "wb") as a:

std = {} for i in
range(30):

std['name'] = input("Enter name: ")

std['age'] = int(input("Enter age: "))


std['class'] = input("enter your class")
pickle.dump(std, a) with open("abc.txt",
"rb") as a:

std = pickle.load(a) print(std)

OUTPUT:
Q-27WAP to read data from student.dat.
SOLUTION: import pickle with
open('student.dat','rb') as z:

data = pickle.load(z) print(data)

OUTPUT:
Q-28 WAP to a binary file called emp.dat and write into it employee details of some
employees available in the form of dictionary.
DETAILS: Name,ID,Age,Salary SOLUTION:

import pickle with


open("emp.txt", "wb") as f:

a = {} for i in

range(1):
a['name'] = input("Enter name: ")

a['ID'] = int(input("Enter ID: ")) a['age']

= int(input("enter age:")) a['salary'] =

int(input("Enter salary: "))


pickle.dump(a, f)

OUTPUT:
Q- 29 Write a menu driven code to perform all binary operations on binary file.

SOLUTION:

import pickle def write(): with


open("student.dat","wb") as f:

record=[]
while True:
rno=int(input("enter your roll no:"))
marks = int(input("enter your marks:"))
name = input("enter your name:")
data=[rno,name,marks]
record.append(data) ch = input("more
records y/n") if ch in "Nn":

break

pickle.dump(record,f)
print("record added")

def read():

print("contents in file") with

open("student.dat","rb") as f:
while True:

s=pickle.load(f)

for i in s:
print(i)
def append(): with

open("student.dat","rb") as f:

print("append data in file") rec =


pickle.load(f) while True:
rno = int(input("enter your roll no:"))

name = input("enter your name:")


marks = int(input("neter your marks:"))
data = [rno,name,marks]

rec.append(data) ch = input("more
records y/n:") if ch in "Nn": break

f.seek(0)
pickle.dump(rec,f)
print("record appended")

def search(): with


open("student.dat","rb") as f:

r=int(input("enter your roll no to be searched :"))

found = 0 try: while True:

s=pickle.load(f)

for I in s: if
I[0]==r:

print(i) found
=1 break

except Exception:
f.close() if

found == 0:

print("sorry no such record exist")

def update(): with


open("student.dat","rb+") as f:

r=int(input("enter your roll no. whose details to be updated"))

f.seek(0) try: while True: rpose = f.tell() s=


pickle.load() print(s) for I in s: if i[0]==r:

i[1] = input("enter new roll no:")

I[2] = int(input("enter new marks:"))


f.seek(repos)

pickle.dump(s,f)

break except

Exception:

f.close()

def delete(): with


open("student.dat","wb") as f:

s = pickle.load(f) f.close() r =

int(input("enter roll no. to be deleted"))


with open("student.dat","wb") as f:

print(s)

reclst =
for i in s:

if i[0]:

continue

reclst.append(i)
pickle.dump(reclst,f)

def mainmenu():
print("1.write")

print("2.read")
print("3.append")
print("4.search")
print("5.update")
print("6.delete")
print("7.exit") while True:
mainmenu() ch =
int(input("enter your choice"))

if ch==1: write() elif ch==2:

read() elif ch==3: append()

elif ch==4: search() elif


ch==5: update() elif ch==6:

delete() elif ch==7:


exit()
OUTPUT:
Q-30 Write a function to write records in std.csv .

SOLUTION:

import csv

def write_records_to_csv(filename="std.csv"):

with open(filename, "w", newline="") as csvfile:

writer = csv.writer(csvfile)

num_records = int(input("How many records do you want to enter? "))

for _ in range(num_records):

record = eval(input("Enter a record (e.g., ['John Doe', 25, 'Male']): "))

writer.writerow(record)

print("Record added!")

write_records_to_csv()

output:
Q-31 write a user-defined function and input book details [book no. , author name , price]
in the form of list using CSV file.

SOLUTION:

import csv

def input_book_details(filename="books.csv"):

with open(filename, "a", newline="") as csvfile:

writer = csv.writer(csvfile)

while True:

book_no = input("Enter book number: ")

author_name = input("Enter author name: ")

price = input("Enter price: ")

book_details = [book_no, author_name, price]

writer.writerow(book_details)

print("Book details added!")

add_more = input("Add more books? (y/n): ")

if add_more.lower() == 'n':

break

input_book_details()

output:
Q-32 write a menu-driven code to perform read,write and search operatons in a csv file.

SOLUTION:

import csv

def input_book_details(filename="books.csv"):

with open(filename, "a", newline="") as csvfile:

writer = csv.writer(csvfile)

while True:

book_no = input("Enter book number: ")

author_name = input("Enter author name: ")

price = input("Enter price: ")

book_details = [book_no, author_name, price]

writer.writerow(book_details)

print("Book details added!")

add_more = input("Add more books? (y/n): ")

if add_more.lower() == 'n':

break

def read_book_details(filename="books.csv"):

with open(filename, "r") as csvfile:

reader = csv.reader(csvfile)

for row in reader:

print(f"Book No: {row[0]}, Author: {row[1]}, Price: {row[2]}")

def search_book_details(filename="books.csv", book_no=None):

with open(filename, "r") as csvfile:


reader = csv.reader(csvfile)

found = False

for row in reader:

if row[0] == book_no:

print(f"Book No: {row[0]}, Author: {row[1]}, Price: {row[2]}")

found = True

break

if not found:

print("Book not found!")

def main():

while True:

print("\nMenu:")

print("1. Add book details")

print("2. Read book details")

print("3. Search book details")

print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":

input_book_details()

elif choice == "2":

read_book_details()

elif choice == "3":

book_no = input("Enter book number to search: ")


search_book_details(book_no=book_no)

elif choice == "4":

break

else:

print("Invalid choice!")

if __name__ == "__main__":

main()

OUTPUT
Q-33 WAP to implement all basic operations [push,pop,display].

SOLUTION:

s = []

c = 'y'

while c == 'y':

print('1. Push')

print('2. Pop')

print('3. Display')

choice = int(input('Enter your choice: '))

if choice == 1:

n = int(input('Enter a number: '))

s.append(n)

elif choice == 2:

if s == []:

print('Stack is empty')

else:

print('Deleted element is', s.pop())

elif choice == 3:

l = len(s)

for i in range(l-1, -1, -1):

print(s[i])

else:

print('Invalid choice')

c = input('Do you want to continue? (y/n): ')


OUTPUT:
Q-34 WAF to create stack called "ABC", to perform The basic operations on Stack using list.

List contains the 2 values (Employee No., Name) should include options for addition,
deletion, to view topmost element (peek()) and display of Employee details.

SOLUTIONS:

stack = []

def push(employee_details):

stack.append(employee_details)

print(f"Employee {employee_details[1]} (No: {employee_details[0]}) added to the stack.")

def pop():

if stack:

popped_item = stack.pop()

print(f"Employee {popped_item[1]} (No: {popped_item[0]}) removed from the stack.")

return popped_item

else:

print("Stack is empty!")

return None

def peek():

if stack:

top_item = stack[-1]

print(f"Topmost element: Employee {top_item[1]} (No: {top_item[0]})")

return top_item

else:

print("Stack is empty!")

return None
def display():

if stack:

print("Employee Details:")

for i, item in enumerate(stack):

print(f"Employee {i+1}: No: {item[0]}, Name: {item[1]}")

else:

print("Stack is empty!")

while True:

print("\nStack Operations:")

print("1. Push (Add employee)")

print("2. Pop (Remove employee)")

print("3. Peek (View top element)")

print("4. Display")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == "1":

emp_no = input("Enter employee number: ")

emp_name = input("Enter employee name: ")

push([emp_no, emp_name])

elif choice == "2":

pop()

elif choice == "3":


peek()

elif choice == "4":

display()

elif choice == "5":

break

else:

print("Invalid choice!")

OUTPUT:

You might also like