Exceptional Handling-1
Exceptional Handling-1
1. Write a code so that an error is printed if the number conversion is not successful.
val = input("Enter a number: ")
try:
pval = int(val)
except ValueError:
print("Error: Conversion to integer failed.")
Output
Enter a number: 23
Enter a number: python
Error: Conversion to integer failed.
2. Defines a function divide_numbers that performs division between two numbers x and y.
def divide_numbers(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Division result:", result)
finally:
print("End of division operation.")
divide_numbers(10, 2)
divide_numbers(10, 0)
Output
Division result: 5.0
End of division operation.
Error: Division by zero is not allowed.
End of division operation.
3. Write a Python program that continuously prompts the user to enter two numbers and performs
division.
loop = 1
while loop == 1:
try:
a = int(input('Enter the first number: '))
b = int(input('Enter the second number: '))
quotient = a / b
except ValueError:
print("Error: Please enter only numbers")
except ZeroDivisionError:
print("\n Error: Second number should not be zero")
except TypeError:
print("\n Unsupported operation: Check the data type")
else:
print("Great")
finally:
print("Program execution completed")
loop = int(input('Press 1 to try again: '))
continue
Data File Handling
1. 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.
input.txt
In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.
output.txt
In the beginning there was chaos.
Out of the chaos came order.
The universe began to take shape.
Stars formed and galaxies were born.
Life emerged in the vast expanse.
2. Write a code snippet that will create an object called fileout for writing; associate it with the
filename 'STRS'. The code should keep on writing strings to it as long as the user wants.
Output
Enter a string: Hello
Want to enter more strings?(y/n)...y
Enter a string: Yenika
Want to enter more strings?(y/n)...n
filter_records('sports.dat', 'Athletic.dat')
Atheletic.dat
Athletics - Rahul
Athletics - Akash
Athletics - Riya
4. Write a program to count the number of uppercase alphabets present in a text file "Poem.txt".
Poem.txt
PYTHON is a Popular Programming Language
with open("Poem.txt", 'r') as file:
text = file.read()
count = 0
for char in text:
if char.isupper():
count += 1
print(count)
5. Write a program to count the words "to" and "the" present in a text file "Poem.txt".
Poem.txt
To be or not to be, that is the question.
The quick brown fox jumps over the lazy dog.
To infinity and beyond!
The sun sets in the west.
To be successful, one must work hard.
to_count = 0
the_count = 0
Output
count of 'to': 4
count of 'the': 5
6. Write a program that copies one file to another. Have the program read the file names from
user.
def copy_file():
source_file = input("Enter the source file name (with extension): ")
destination_file = input("Enter the destination file name (with extension): ")
7. Write a program that reads characters entered by the user one by one. All lower case characters
get stored inside the file 'LOWER', all upper case characters get stored inside the file 'UPPER'
and all other characters get stored inside file 'OTHERS'.
lower_file = open("LOWER.txt", 'w')
upper_file = open("UPPER.txt", 'w')
others_file = open("OTHERS.txt", 'w')
ans = 'y'
while ans == 'y':
char = input("Enter a character: ")
if char.islower():
lower_file.write(char + "\n")
elif char.isupper():
upper_file.write(char + "\n")
else:
others_file.write(char + "\n")
ans = input("Want to enter a character? (y/n): ")
lower_file.close()
upper_file.close()
others_file.close()
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
Want to enter a character? (y/n): y
Enter a character: c
Want to enter a character? (y/n): y
Enter a character: 7
Want to enter a character? (y/n): y
Enter a character: @
Want to enter a character? (y/n): n
8. Write a program to search the names and addresses of persons having age more than 30 in the
data list of persons stored in a text file.
Persons.txt
Samyukta, Mumbai, 35
Anubhav, Chennai, 28
Aniket, Hyderabad, 42
Sarth, Bangalore, 31
f = open('Persons.txt', 'r')
lines = f.readlines()
for line in lines:
data = line.strip().split(',')
if len(data) >= 3 and int(data[2]) > 30:
print('Name:', data[0], 'Address:', data[1])
f.close()
Output
Name: Samyukta Address: Mumbai
Name: Aniket Address: Hyderabad
Name: Sarth Address: Bangalore
9. Write a program to accept string/sentences from the user till the user enters "END". Save the data
in a text file and then display only those sentences which begin with an uppercase alphabet.
f = open("new.txt", "w")
while True:
st = input("Enter next line:")
if st == "END":
break
f.write(st + '\n')
f.close()
f = open("new.txt", "r")
while True:
st = f.readline()
if not st:
break
if st[0].isupper():
print(st)
f.close()
Output
Enter next line:Hello world
Enter next line:welcome to
Enter next line:Python programming
Enter next line:END
Hello world
Python programming
10. Write a function in Python to count and display the number of lines starting with alphabet 'A'
present in a text file "LINES.TXT".
LINES.TXT
A boy is playing there.
There is a playground.
An aeroplane is in the sky.
A cricket match is being played.
def count_lines(file_name):
count = 0
with open(file_name, 'r') as file:
for line in file:
if line.strip().startswith('A'):
count += 1
print(count)
count_lines("LINES.TXT")
Output
3
11. Write a function to insert a sentence in a text file, assuming that text file is very big and can't fit
in computer's memory.
insert.txt
Bees hum
leaves rustle
Waves crash
nature's voice whispers
insert.txt
Bees hum
leaves rustle
Waves crash
nature's voice whispers
life's essence glimmers
12. Write a program to read a file 'Story.txt' and create another file, storing an index of 'Story.txt',
telling which line of the file each word appears in. If word appears more than once, then index
should-show all the line numbers containing the word.
Story.txt
The cat sleeps
The dog barks
The cat jumps
The sun shines
word_index = {}
file = open('Story.txt', 'r')
line_number = 1
lines = file.readlines()
for line in lines:
words = line.strip().split()
for word in words:
if word in word_index:
word_index[word].append(str(line_number))
else:
word_index[word] = [str(line_number)]
line_number += 1
file.close()
index.txt
The:1, 2, 3, 4
cat:1, 3
sleeps:1
dog:2
barks:2
jumps:3
sun:4
shines:4
13. Write a program to accept a filename from the user and display all the lines from the file which
contain Python comment character '#'.
notes.txt
Welcome to the Garden of Dreams
#where the ordinary becomes extraordinary
#the impossible becomes possible.
file_name = input("Enter the filename: ")
file = open(file_name, 'r')
lines = file.readlines()
for line in lines:
if '#' in line:
print(line)
file.close()
Output
Enter the filename: notes.txt
#where the ordinary becomes extraordinary
#the impossible becomes possible.
14. Write a function Remove_Lowercase() that accepts two file names, and copies all lines that do
not start with lowercase letter from the first file into the second file.
file1.txt
Dew on petals, morning's gift.
silent moon, silver glow.
Winds whisper, secrets shared.
rain's embrace, earth's renewal.
input_file = 'file1.txt'
output_file = 'file2.txt'
Remove_Lowercase(input_file, output_file)
15. Write a Python program to display the size of a file after removing EOL characters, leading and
trailing white spaces and blank lines.
sample.txt
The sky is blue\n
Output
Original file size: 126
Cleaned file size: 74
Stack
1. Write a program to reverse a string using stack.
Answer-:
def push(stack, item):
stack.append(item)
def pop(stack):
if stack == []:
return
return stack.pop()
def reverse(string):
n = len(string)
stack = []
for i in range(n):
push(stack, string[i])
string = ""
for i in range(n):
string += pop(stack)
return string
string = input("Enter a string: ")
print("String:", string)
reversedStr = reverse(string)
print("Reversed String:", reversedStr)
Output
Enter a string: Hello World
String: Hello world
Reversed String: dlrow olleH
2. Write a program to create a Stack for storing only odd numbers out of all the numbers entered
by the user. Display the content of the Stack along with the largest odd number in the Stack.