I'd like to raise a TypeError when the parameter of a method in a class is non-integer, but I failed. The code is as below, I put a "N" in the first parameter and expected to get a TypeError, and the printing of " can't set the Rectangle to a non-integer value ", but what I got instead is "Traceback (most recent call last): File "/Users/Janet/Documents/module6.py", line 19, in r1.setData(N,5) NameError: name 'N' is not defined"
class Rectangle:
def __init__ (self):
self.height = 0
self.width = 0
def setData(self, height, width):
if type(height) != int or type(width) != int:
raise TypeError()
if height <0 or width <0:
raise ValueError()
self.height = height
self.width = width
def __str__(self):
return "height = %i, and width = %i" % (self.height, self.width)
r1 = Rectangle()
try:
r1.setData(N,5)
except ValueError:
print ("can't set the Rectangle to a negative number")
except TypeError:
print ("can't set the Rectangle to a non-integer value")
print (r1)