Errors and Exceptions Homework -

Problem 1

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


In [2]:
for i in ['a','b','c']:
    try: 
        print i**2
    except:
        print "Not an integer"


Not an integer
Not an integer
Not an integer

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:
    print "x/y Division could not be performed"
finally:
    print "All done!"


x/y Division could not be performed
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 [6]:
def ask():
    while True:
        try:
            val = int(raw_input("Enter a number :"))
        except:
            print "Enter a proper number"
            continue
        else:
            print "The square of the entered numer is :", val**2
            break

In [7]:
ask()


Enter a number :e
Enter a proper number
Enter a number :r
Enter a proper number
Enter a number :3
The square of the entered numer is : 9

Great Job!