EXCEPTION HANDLING
IN PYTHON
🌐 Website:- www.pythonhomeworkhelp.com
📧 Email:- support@pythonhomeworkhelp.com
📲 Call/WhatsApp:- +1 (315) 557-6473
Question 1.
Write a Python program that reads a CSV file containing integers and calculates
the average of each column in the file. Handle the exceptions that may arise if
the file does not exist, if the file is empty, or if any of the elements in the file is
not an integer.
Solution :
import csv
class EmptyFileError(Exception):
pass
class NonIntegerError(Exception):
pass
try:
with open("file.csv") as f:
reader = csv.reader(f)
data = list(reader)
if len(data) == 0:
www.pythonhomeworkhelp.com
raise EmptyFileError
averages = []
for i in range(len(data[0])):
total = 0
count = 0
for j in range(len(data)):
try:
num = int(data[j][i])
total += num
count += 1
except ValueError:
pass
except IndexError:
pass
if count == 0:
raise NonIntegerError
averages.append(total / count)
print("Averages: ", averages)
www.pythonhomeworkhelp.com
except FileNotFoundError:
print("Error: file not found")
except EmptyFileError:
print("Error: the file is empty")
except NonIntegerError:
print("Error: some columns contain only non-integer values")
Question 2:
Write a Python function that takes a list of integers as input and returns the
average of the integers. If the list is empty, raise a custom exception
"EmptyListError". If any of the elements in the list is not an integer, skip that
element and continue calculating the average.
Solution :
class EmptyListError(Exception):
pass
www.pythonhomeworkhelp.com
class EmptyListError(Exception):
pass
def difference(lst):
try:
if len(lst) == 0:
raise EmptyListError
nums = []
for i in lst:
if isinstance(i, int):
nums.append(i)
if len(nums) == 0:
raise ValueError
return max(nums) - min(nums)
except EmptyListError:
print("Error: the list is empty")
except ValueError:
print("Error: all elements in the list are non-integer values").
www.pythonhomeworkhelp.com
Question 3:
Write a Python program that reads a file containing integers and calculates the
sum of each row in the file. Handle the exceptions that may arise if the file does
not exist, if the file is empty, or if any of the elements in the file is not an integer.
Solution:
class EmptyFileError(Exception):
pass
class NonIntegerError(Exception):
pass
try:
with open("file.txt") as f:
data = f.readlines()
if len(data) == 0:
raise EmptyFileError
www.pythonhomeworkhelp.com
sums = []
for row in data:
row_sum = 0
nums = row.split()
for num in nums:
try:
row_sum += int(num)
except ValueError:
pass
if len(nums) == 0:
raise NonIntegerError
sums.append(row_sum)
print("Sums: ", sums)
except FileNotFoundError:
print("Error: file not found")
except EmptyFileError:
print("Error: the file is empty")
except NonIntegerError:
print("Error: some rows contain only non-integer values").
www.pythonhomeworkhelp.com

Python Homework Help

  • 1.
    EXCEPTION HANDLING IN PYTHON 🌐Website:- www.pythonhomeworkhelp.com 📧 Email:- support@pythonhomeworkhelp.com 📲 Call/WhatsApp:- +1 (315) 557-6473
  • 2.
    Question 1. Write aPython program that reads a CSV file containing integers and calculates the average of each column in the file. Handle the exceptions that may arise if the file does not exist, if the file is empty, or if any of the elements in the file is not an integer. Solution : import csv class EmptyFileError(Exception): pass class NonIntegerError(Exception): pass try: with open("file.csv") as f: reader = csv.reader(f) data = list(reader) if len(data) == 0: www.pythonhomeworkhelp.com
  • 3.
    raise EmptyFileError averages =[] for i in range(len(data[0])): total = 0 count = 0 for j in range(len(data)): try: num = int(data[j][i]) total += num count += 1 except ValueError: pass except IndexError: pass if count == 0: raise NonIntegerError averages.append(total / count) print("Averages: ", averages) www.pythonhomeworkhelp.com
  • 4.
    except FileNotFoundError: print("Error: filenot found") except EmptyFileError: print("Error: the file is empty") except NonIntegerError: print("Error: some columns contain only non-integer values") Question 2: Write a Python function that takes a list of integers as input and returns the average of the integers. If the list is empty, raise a custom exception "EmptyListError". If any of the elements in the list is not an integer, skip that element and continue calculating the average. Solution : class EmptyListError(Exception): pass www.pythonhomeworkhelp.com
  • 5.
    class EmptyListError(Exception): pass def difference(lst): try: iflen(lst) == 0: raise EmptyListError nums = [] for i in lst: if isinstance(i, int): nums.append(i) if len(nums) == 0: raise ValueError return max(nums) - min(nums) except EmptyListError: print("Error: the list is empty") except ValueError: print("Error: all elements in the list are non-integer values"). www.pythonhomeworkhelp.com
  • 6.
    Question 3: Write aPython program that reads a file containing integers and calculates the sum of each row in the file. Handle the exceptions that may arise if the file does not exist, if the file is empty, or if any of the elements in the file is not an integer. Solution: class EmptyFileError(Exception): pass class NonIntegerError(Exception): pass try: with open("file.txt") as f: data = f.readlines() if len(data) == 0: raise EmptyFileError www.pythonhomeworkhelp.com
  • 7.
    sums = [] forrow in data: row_sum = 0 nums = row.split() for num in nums: try: row_sum += int(num) except ValueError: pass if len(nums) == 0: raise NonIntegerError sums.append(row_sum) print("Sums: ", sums) except FileNotFoundError: print("Error: file not found") except EmptyFileError: print("Error: the file is empty") except NonIntegerError: print("Error: some rows contain only non-integer values"). www.pythonhomeworkhelp.com