-1

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)
Shengjing
  • 63
  • 1
  • 9

2 Answers2

0

Consider using typeof, as in this question: Checking whether a variable is an integer or not

You have some bad formatting in your listing, by the way. Change this:

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

to this:

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
Community
  • 1
  • 1
mark-henry
  • 11
  • 4
  • 1
    Did you mean `isinstance`? Although that would cover classes inheriting from `int`, it likely won't solve OP's problem. – tdelaney May 09 '16 at 23:35
0

Edit answer to reflect the new and more accurate explanation. As @Evert says, N is not defined, so Python is looking what the variable N is, and it isn't finding anything. If you instead wrote "N" (making it a string), then your program should return TypeError.

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)

This prints out: "can't set the Rectangle to a non-integer value height = 0, and width = 0"

Sisoma Munden
  • 78
  • 2
  • 8