ACFrOgAq5EYCrQ5nXqJWrcQ4yzz5-NYV8 T7zj b4jkY2vsDrV9CN3dzoxP6wQYbyN2G78mB7nxysG1hV1pHTxhGW15Zo vxTlzrDG9ZSNllZH0GtDC2l6pEs-x2O2lANvTEXofxZ9mFy4jWt7PI
ACFrOgAq5EYCrQ5nXqJWrcQ4yzz5-NYV8 T7zj b4jkY2vsDrV9CN3dzoxP6wQYbyN2G78mB7nxysG1hV1pHTxhGW15Zo vxTlzrDG9ZSNllZH0GtDC2l6pEs-x2O2lANvTEXofxZ9mFy4jWt7PI
SCIENCE
PRACTICAL FILE
1
CERTIFICATE
Date: ___________
Roll No.: _______________
Principal’s Sign
2
ACKNOWLEDGEMENT
INDEX
Sr. No. Title of Program Pg. No.
3
1. PRINT THE WORD- NEGATIVE/POSITIVE/ZERO 6
4
24. FUNCTION TO COUNT THE NUMBER OF A AND M 18
5
print('POSITIVE')
elif num<0:\
print('NEGATIVE')
else:
print('ZERO')
SAMPLE OUTPUT:
SAMPLE OUTPUT:
6
print(x)
SAMPLE OUTPUT:
SAMPLE OUTPUT:
7
6. PRINT SUM OF INTEGERS FROM N TO 2*N
AIM:
Write a program that reads an integer N from the keyboard computes and displays
the sum of the numbers from N to (2*N) if N is non negative. If N is a negative
number, then it’s the sum of the numbers from (2*N) to N. The starting and ending
points are included in the sum.
SOURCE CODE:
N = int(input("Enter: "))
if N>=0:
x = sum(range(N, 2*N+1))
else:
x = sum(range(2*N, N+1))
print("The sum of the numbers:", x)
SAMPLE OUTPUT:
8
print(a)
x = a + b
a = b
b = x
count+= 1
SAMPLE OUTPUT:
SAMPLE OUTPUT:
9
print(f"The value does not exist in the
dictionary.")
x = int(input("Value you want to check:"))
check(x)
SAMPLE OUTPUT:
10.DICE SIMULATOR
AIM:
Write a random number generator that generates random numbers between 1 and 6
(simulates a dice)
SOURCE CODE:
import random
print (random.randint(1,6))
SAMPLE OUTPUT:
4
10
SOURCE CODE:
def convert(USD):
inr=USD/83.99
return inr
USD=float(input("Amount ins USD:"))
SAMPLE OUTPUT:
4233.00
13:
AIM:
Write a program to have the following functions:
a) A function that takes a number as an argument and calculates a cube for it. The
function does not return a value. If there is no value passed to the function
in function call, the function should calculate cube of 2
b) A function that takes two char arguments and returns True if both arguments
are equal otherwise False.
SOURCE CODE:
def cube(X=2):
Y = X** 3
print("The cube of {X} is: {Y}")
14.
AIM:
Write a function that receives two numbers and generates a random number from
that range. Using this function, the main program should be able to print three
11
numbers randomly.
SOURCE CODE:
import random
def generator(start, end):
return random.randint(start, end)
x = int(input("Enter the start: "))
y = int(input("Enter the end: "))
print("Three random numbers:")
for i in range(4):
z = generator(x, y)
print(z)
SAMPLE OUTPUT:
Three random numbers:
25
22
30
15.
AIM:
Write a function that receives two string arguments and checks whether they are
same length strings(returns True else False).
SOURCE CODE:
def length(x, y):
return len(x) == len(y)
x=input('Enter String 1:')
y=input("Enter String 2: ")
length(x,y)
SAMPLE OUTPUT:
The two strings have the same length.
12
16.
AIM:
Write a function namely nthRoot() that receives two parameters x and n and returns
nth root of x. i.e x 1/n . The default value of n is 2.
SOURCE CODE:
def nthRoot(x, n = 2):
return x ** (1/n)
y = nthRoot(x, n)
print("The", n, "th root of", x, "is:", y)
z = nthRoot(x)
print("The square root of", x, "is:", z)
SAMPLE OUTPUT:
17.
AIM:
Write a function that takes a number n and then returns a randomly
generated number having exactly n digits(not starting with zero).
SOURCE CODE:
import random
def generate_number(n):
x = 10 ** (n - 1)
y = (10 ** n) - 1
return random.randint(x, y)
n = int(input("Enter n:"))
13
random_number = generate_number(n)
print("Random number:", random_number)
SAMPLE OUTPUT:
18.
AIM:
Write a function that takes two numbers and returns the number that has the
minimum one’s digit.
SOURCE CODE:
def min_digit(num1, num2):
x = num1 % 10
y = num2 % 10
if x < y:
return x
else:
return y
SAMPLE OUTPUT:
19.
AIM:
Read a text file line by line and display each word separated by a #
SOURCE CODE:
def hash(filename):
try:
with open(filename, 'r') as file:
for i in file:
words = i.strip().i()
print('#'.join(words))
except FileNotFoundError:
14
print(f"The file '{filename}' does not exist.")
SAMPLE OUTPUT:
20.
AIM:
Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file. Remove all the lines that contain the character 'a' in a file and
write it to another file.
SOURCE CODE:
def filter_file(input_file, output_file):
vowels = 'aeiouAEIOU'
vowels= consonants = uppercase = lowercase= 0
try:
with open(input_file, 'r') as file, open(output_file,
'w') as new_file:
for line in file:
15
new_file.write(line)
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase characters: {uppercase}")
print(f"Lowercase characters: {lowercase}")
except FileNotFoundError:
print(f"The file '{input_file}' does not exist.")
SAMPLE OUTPUT:
21.
AIM:
Write a function DISPLAYWORDS() in python to read lines from a text file
STORY.TXT and display those words which are less than 4 characters
SOURCE CODE:
def DISPLAYWORDS():
try:
with open('STORY.TXT', 'r') as file:
for line in file:
words = line.strip().split()
for word in words:
if len(word)<4:
print(word)
except FileNotFoundError:
print("The file 'STORY.TXT' does not exist.")
SAMPLE OUTPUT:
16
22.
AIM:
Write a program that reads a text file and creates another file that is identical except
that every sequence of consecutive blank spaces is replaced by a single space.
SOURCE CODE:
def remove_extra_spaces(input_file, output_file):
file=open(input_file, 'r')
new_file= open(output_file, 'w+')
for i in file:
x = ' '.join(i.split())
new_file.write(x + '\n')
SAMPLE OUTPUT:
23.
AIM:
Write a program to count the words “to” and "the” present in a text file “Poem.txt”.
SOURCE CODE:
def count_words_in_file(poem):
to_count = 0
the_count = 0
file=open(poem.txt, 'r')
for line in file:
words = line.lower().split()
to_count += words.count("to")
the_count += words.count("the")
print(f"The word 'to' appears {to_count} times.")
print(f"The word 'the' appears {the_count} times.")
SAMPLE OUTPUT:
17
24.
AIM:
Write a function AMCount() in Python, which should read each character of a text
file STORY.TXT. It should count and display the occurrence of alphabet A and M
including (small case a and m).
SOURCE CODE:
def AMCount():
a_count=0
m_count=0
file=open('STORY.TXT', 'r')
for i in file:
for char in i:
if char == 'A' or char == 'a':
a_count+= 1
25.
AIM:
Write a program to count the number of uppercase alphabets present in a text file
Article.txt.
SOURCE CODE:
def count_uppercase_characters(filename):
18
uppercase_count = 0
file= open(filename, 'r')
for i in file:
for x in i:
if x.isupper():
uppercase_count += 1
print(f"The number of uppercase alphabets in
'{filename}' is: {uppercase_count}")
SAMPLE OUTPUT:
26.
AIM:
Write a program that copies one file to another. Have the program read the file
names from the user.
SOURCE CODE:
source= input("Enter name of source file: ")
destination= input("Enter name of destination file: ")
src=open(source, 'r')
dest=open(destination, 'w')
for line in src:
dest.write(line)
print(f"File '{source}' has been copied to '{destination}'.")
SAMPLE OUTPUT:
source: destination:
27.
AIM:
Write a program that appends the contents of one file to another. Have the program
read the file names from the user.
SOURCE CODE:
19
def append_file_contents():
source= input("Entername of source file: ")
destination= input("Enter name of destination file: ")
src= open(source, 'r')
dest=open(destination, 'a')
for line in src:
dest.write(line)
print(f"Contents of '{source}' have been appended to
'{destination}'.")
SAMPLE OUTPUT:
28.
AIM:
Write a program that reads characters from the keyboard one by one. All lower
case characters get stored inside the file LOWER, all upper case characters fet
stored inside the file UPPER and all other characters get stored inside the file
OTHERS.
SOURCE CODE:
lower= open("LOWER.txt", 'w')
upper = open("UPPER.txt", 'w')
others = open("OTHERS.txt", 'w')
ans = 'y'
while ans == 'y':
x = input("Enter a character: ")
if x.islower():
lower.write(x + "\n")
elif x.isupper():
upper.write(x + "\n")
else:
others.write(x + "\n")
ans = input("Want to enter a character? (y/n): ")
20
SAMPLE OUTPUT:
Enter a character: e
Want to enter a character? (y/n): y
Enter a character: A
Want to enter a character? (y/n): y
Enter a character: D
29.
AIM:
Write a function in Python to count and display the number of lines starting with A
present in the text file LINES.TXT.
SOURCE CODE:
def count_lines(file_name):
count = 0
file= open(file_name, 'r')
for i in file:
if i.strip().startswith('A'):
count += 1
print(count)
count_lines("LINES.TXT")
SAMPLE OUTPUT:
3
30.
AIM:
Write a function SHOW_WORDS() in Python to read the content of a text file
“NOTES.TXT” and display only such lines of the file which have exactly 5 words in
them.
SOURCE CODE:
def Show_words(file_name):
file= open(file_name, 'r')
21
for i in file:
words = i.strip().split()
if len(words) == 5:
print(i.strip())
Show_words('NOTES.TXT')
SAMPLE OUTPUT:
This is a sample file.
31.
AIM:
Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
SOURCE CODE:
import pickle
def create_file(name, roll_number):
with open('students.bin', 'ab') as file:
pickle.dump((name, roll_number), file)
def search_roll_number(roll_number):
file= open('students.bin', 'rb')
while True:
try:
name, number = pickle.load(file)
if number == roll_number:
return name
except EOFError:
break
return None
name = search_roll_number(1)
if name is not None:
print(f'Name: {name}')
else:
print('Roll number not found.')
SAMPLE OUTPUT:
22
32.
AIM:
Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
SOURCE CODE:
import pickle
def create_binary_file(filename):
data = []
while True:
roll_number = input("Enter roll number (or 'exit' to
stop): ")
if roll_number.lower() == 'exit':
break
name = input("Enter name: ")
marks = input("Enter marks: ")
data.append((roll_number, name, marks))
file= open(filename, 'wb')
pickle.dump(data, file)
print(f"Data has been written to {filename}.")
23
file= open(filename, 'wb')
pickle.dump(data, file)
print(f"Marks for roll number {roll_number} have
been updated to {new_marks}.")
except FileNotFoundError:
print(f"The file '{filename}' does not exist.")
SAMPLE OUTPUT:
33.
AIM:
A binary file “Book.dat” has structure [Book_No,Book_Name, Author, Price].
a) Write a user defined function CreateFile() to input data for a record and add to
Book.dat
b) Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given author are stored
in the binary file “Book.dat”
SOURCE CODE:
import pickle
def CreateFile(filename):
file=open(filename, 'wb')
while True:
book_no = input("Enter Book Number (or 'exit' to stop):
")
if book_no.lower() == 'exit':
break
else:
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Price: "))
24
record = (book_no, book_name, author, price)
pickle.dump(record, file)
print(f"Data has been written to {filename}.")
34.
AIM:
A file sports.dat contains information in the following format: Event – Participant
Write a function that would read contents from file sports.dat and creates a file
named Atheletic.dat copying only those records from sports.dat where the event
name is “Athletics”.
SOURCE CODE:
def filter_records(input_file, output_file):
f_in= open(input_file, 'r')
with open(output_file, 'w') as f_out:
for line in f_in:
25
event, participant = line.strip().split(' - ')
if event == 'Athletics':
f_out.write(line)
filter_records('sports.dat', 'Athletic.dat')
SAMPLE OUTPUT:
35.
AIM:
Consider the definition of the dictionary STAFF below.
Staff={‘staffcode’:___, ‘name’: ______}.
Create a method – staffcreate() . Ask user to enter details for the dictionary and
store the same in STAFF.dat.
Create another method – searchstaff() to search and display the content from
staff.dat
SOURCE CODE:
import pickle
def search_and_display_staff(staff_code):
found = False
try:
file = open("staff.dat", "rb")
while True:
staff_data = pickle.load(file)
if staff_data['Staffcode'] == staff_code:
print("Staffcode:",
staff_data['Staffcode'])
print("Name:", staff_data['Name'])
found = True
except EOFError:
if found == False:
26
print("End of file reached. No such records
found.")
else:
print("Search Successful")
file.close()
search_and_display_staff('S0105')
SAMPLE OUTPUT:
36.
AIM:
Write a python program to read the given csv file with tab delimiter.
SOURCE CODE:
import csv
37.
AIM:
Create a CSV file by entering user-id and password, read and search the password
for given user id.
Write a function that reads a csv file and creates another csv file with the same
content except the lines beginning with ‘check’.
27
SOURCE CODE:
import csv
def create_csv_file(filename):
file= open(filename, 'w', newline='')
writer = csv.writer(file)
while True:
user_id = input("Enter User ID (or 'exit' to stop):
")
if user_id.lower() == 'exit':
break
password = input("Enter Password: ")
writer.writerow([user_id, password])
print(f"Data has been written to {filename}.")
28
writer.writerow(row)
print(f"Filtered data has been written to
{output_filename}.")
SAMPLE OUTPUT:
38.
AIM:
Write a python program to implement a stack using a list data structure.
SOURCE CODE:
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed: {item}")
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
item = self.stack.pop()
print(f"Popped: {item}")
return item
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
29
return len(self.stack)
def display(self):
print("Stack contents:", self.stack)
SAMPLE OUTPUT:
39.
AIM:
Write a menu driven program to find the sum, difference, multiplication and division
of two numbers
SOURCE CODE:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
30
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '5':
print("Exiting the program.")
break
if choice in ['1', '2', '3', '4']:
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
result = add(num1, num2)
print(f"The sum of {num1} and {num2} is:
{result}")
elif choice == '2':
result = subtract(num1, num2)
print(f"The difference of {num1} and {num2}
is: {result}")
elif choice == '3':
result = multiply(num1, num2)
print(f"The multiplication of {num1} and
{num2} is: {result}")
elif choice == '4':
result = divide(num1, num2)
print(f"The division of {num1} by {num2}
is: {result}")
else:
print("Invalid choice. Please enter a number
between 1 and 5.")
SAMPLE OUTPUT:
31
40.
AIM:
Write a Menu driven python program to implement a Stack using a list data-
structure.
SOURCE CODE:
def peek(self):
if self.is_empty():
print("Stack is empty! Cannot peek.")
return None
return self.stack[-1]
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
print("Stack contents:", self.stack)
def main():
stack = Stack()
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Check if Empty")
32
print("5. Size")
print("6. Display")
print("7. Exit")
choice = input("Enter your choice (1-7): ")
if choice == '1':
item = input("Enter the item to push: ")
stack.push(item)
elif choice == '2':
stack.pop()
elif choice == '3':
top_item = stack.peek()
if top_item is not None:
print(f"Top item is: {top_item}")
elif choice == '4':
if stack.is_empty():
print("Stack is empty.")
else:
print("Stack is not empty.")
elif choice == '5':
print(f"Size of the stack: {stack.size()}")
elif choice == '6':
stack.display()
elif choice == '7':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a number
between 1 and 7.")
SAMPLE OUTPUT:
33
34