[go: up one dir, main page]

0% found this document useful (0 votes)
51 views11 pages

Exceptional Handling-1

class12 exp handling

Uploaded by

Jigyasa Dhapola
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)
51 views11 pages

Exceptional Handling-1

class12 exp handling

Uploaded by

Jigyasa Dhapola
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/ 11

Exceptional Handling

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.

with open("input.txt", 'r') as f:


with open("output.txt", 'w') as fout:
for line in f:
modified_line = ' '.join(line.split())
fout.write(modified_line + '\n')

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.

fileout = open('STRS.txt', 'w')


ans = 'y'
while ans == 'y':
string = input("Enter a string: ")
fileout.write(string + "\n")
ans = input("Want to enter more strings?(y/n)...")
fileout.close()

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

3. A file 'sports.dat' contains information in the following format: EventName, Participant


Write a function that would read contents from file 'sports.dat' and create a file named
'Athletic.dat' copying only those records from 'sports.dat' where the event name is "Athletics".
sports.dat
Athletics - Rahul
Swimming - Tanvi
Athletics - Akash
Cycling - Kabir
Athletics - Riya
def filter_records(input_file, output_file):
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
for line in f_in:
event, participant = line.strip().split(' - ')
if event == 'Athletics':
f_out.write(line)

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

with open("Poem.txt", 'r') as file:


for line in file:
words = line.split()
for word in words:
if word.lower() == 'to':
to_count += 1
elif word.lower() == 'the':
the_count += 1
print("count of 'to': ", to_count)
print("count of 'the': ", the_count)

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): ")

with open(source_file, 'r') as source:


with open(destination_file, 'w') as destination:
for line in source:
destination.write(line)

print("File copied successfully from”,source_file,” to”,destination_file,”.")


copy_file()

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

LOWER.txt UPPER.txt OTHERS.txt


e A 7
c D @

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

def insert_sentence(file_path, sentence):


file = open(file_path, 'a')
file.write(sentence + '\n')
file.close()
insert_sentence("insert.txt", "life's essence glimmers")

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_file = open('index.txt', 'w')


for word, line_numbers in word_index.items():
line_numbers_str = ", ".join(line_numbers)
index_file.write(word + ":" + line_numbers_str + "\n")
index_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.

def Remove_Lowercase(input_file, output_file):


input_file = open(input_file, 'r')
output_file = open(output_file, 'w')
for line in input_file:
if line.strip() and line[0].isupper():
output_file.write(line)
input_file.close()
output_file.close()

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

Clouds float gently in the sky.

Birds sing sweet melodies.

file = open('sample.txt', 'r')


lines = file.readlines()
original_size = 0
for line in lines:
original_size += len(line)
print("Original file size:", original_size)
file.close()
file = open('sample.txt', 'r')
cleaned_size = 0
for line in file:
cleaned_line = line.strip()
if cleaned_line:
cleaned_size += len(cleaned_line)
file.close()
print("Cleaned file size:", cleaned_size)

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.

def push(stack, item):


stack.append(item)
def pop(stack):
if stack == []:
return
return stack.pop()
def oddStack(num):
if num % 2 == 1:
push(stack, num)
def GetLargest(stack):
elem = pop(stack)
large = elem
while elem != None:
if large < elem:
large = elem
elem = pop(stack)
return large
n = int(input("How many numbers?"))
stack = []
for i in range(n):
number = int(input("Enter number:"))
oddStack(number)
print("Stack created is", stack)
bigNum = GetLargest(stack)
print("Largest number in stack", bigNum)
Output
How many numbers? 3
Enter number:1
Enter number:2
Enter number:3
Stack created is [1,3]
Largest number in the stack 3

You might also like