Errors and Exceptions Homework -

Problem 1

Handle the exception thrown by the code below by using try and except blocks.


In [1]:
for i in ['a','b','c']:
    try: 
        result = i**2
    except TypeError:
        print("Type error attempting to run on {i}".format(i=i))
    else:
        print result


Type error attempting to run on a
Type error attempting to run on b
Type error attempting to run on c

Problem 2

Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'


In [3]:
x = 5
y = 0

try:
    z = x/y
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print 'all done'


Cannot divide by zero
all done

Problem 3

Write a function that asks for an integer and prints the square of it. Use a while loop with a try,except, else block to account for incorrect inputs.


In [4]:
def ask():
    while True:
        try:
            input = int(raw_input("Enter an integer: "))
        except:
            print 'Could not make conversion. Try again'
        else:
            print input**2

In [ ]:
ask()


Enter an integer: 0
0
Enter an integer: 9
81
Enter an integer: 8
64
Enter an integer: e
Could not make conversion. Try again
Enter an integer: 5
25

Great Job!