SlideShare a Scribd company logo
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

More Related Content

Similar to Python Homework Help

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
AnirudhaGaikwad4
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
sunilchute1
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
Simplilearn
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
Albert DeFusco
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Santosh Verma
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
NawalKishore38
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
Mindy McAdams
 
Day2
Day2Day2
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Python advance
Python advancePython advance
Python advance
Deepak Chandella
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Presentation on basics of python
Presentation on basics of pythonPresentation on basics of python
Presentation on basics of python
NanditaDutta4
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
Vishal Dutt
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
YashAgarwal413109
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
J On The Beach
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
Nicola Pedot
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 

Similar to Python Homework Help (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Session - 6
Python Session - 6Python Session - 6
Python Session - 6
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2
 
Day2
Day2Day2
Day2
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Python advance
Python advancePython advance
Python advance
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Presentation on basics of python
Presentation on basics of pythonPresentation on basics of python
Presentation on basics of python
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16
 
Unit-4 PPTs.pptx
Unit-4 PPTs.pptxUnit-4 PPTs.pptx
Unit-4 PPTs.pptx
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 

More from Python Homework Help

Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Complete my Python Homework
Complete my Python HomeworkComplete my Python Homework
Complete my Python Homework
Python Homework Help
 
Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptx
Python Homework Help
 
Basic Python Programming.pptx
Basic Python Programming.pptxBasic Python Programming.pptx
Basic Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptx
Python Homework Help
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
Python Homework Help
 
Perfect Python Homework Help
Perfect Python Homework HelpPerfect Python Homework Help
Perfect Python Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
Python Homework Help
 

More from Python Homework Help (20)

Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Complete my Python Homework
Complete my Python HomeworkComplete my Python Homework
Complete my Python Homework
 
Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptx
 
Basic Python Programming.pptx
Basic Python Programming.pptxBasic Python Programming.pptx
Basic Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptx
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Perfect Python Homework Help
Perfect Python Homework HelpPerfect Python Homework Help
Perfect Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 

Recently uploaded

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 

Recently uploaded (20)

The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 

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 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
  • 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: 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
  • 5. 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
  • 6. 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
  • 7. 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