SlideShare a Scribd company logo
1 of 7
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
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in pythonsunilchute1
 
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 ComputingAlbert 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
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 
Learning Python - Week 2
Learning Python - Week 2Learning Python - Week 2
Learning Python - Week 2Mindy McAdams
 
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!
 
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 pythonNanditaDutta4
 
Python files / directories part16
Python files / directories  part16Python files / directories  part16
Python files / directories part16Vishal Dutt
 
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 2018Codemotion
 

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
 
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
 
Lazy java
Lazy javaLazy java
Lazy java
 

More from Python Homework Help

Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptxPython 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

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Recently uploaded (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

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