Answer to Question #199655 in Python for FORTUNE AIDOO

Question #199655

Describe how catching exceptions can help with file errors. Write three Python examples that actually generate file errors on your computer and catch the errors with try: except: blocks. Include the code and output for each example in your post. 

Describe how you might deal with each error if you were writing a large production program. These descriptions should be general ideas in English, not actual Python code. 


1
Expert's answer
2021-05-28T01:15:19-0400

Example-1

def get_sum_even(lst):
    Sum=0;
    for c in  range(0,len(lst)):
        is_int = True
        try:
           # convert to integer
           int(str(lst[c]))
        except ValueError:
           is_int = False
        if(is_int):
           if( lst[c]%2==0):
               Sum = Sum + lst[c]     
    return(Sum)


s = [2, 3, 5, 4, -1, 2]
print(s)
print("Sum = %d"%get_sum_even(s))


s = [1, 2, 3, 4, 'two',2]
print("\n",s)
print("Sum = %d"%get_sum_even(s))


s = []
print("\n",s)
print("Sum = %d"%get_sum_even(s))


s = ['NA']
print("\n",s)
print("Sum = %d"%get_sum_even(s))


Example-2

def divide(f1, f2):
   try:
       answer = f1/f2
       return answer
   except ZeroDivisionError:
       return 'Divide by zero is not allowed'


print(divide(10,5))
print(divide(10,0))



Example-3

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS