I need to check for floating point numbers inside my class but it doesn't seem to be working. Any suggestions?

class Rectangle:

    def __init__(self, length = 1, width = 1):
        self.__length = length
        self.__width = width

    ##Setters to float
    def set_length(self, length):
        self.__length = float(length)
        try:
            #self.__length = float(length)
            if self.__length > 0.0 and self.__length < 20.0:
                print "Value is in range.  You may continute."
            else:
                raise ValueError
        except ValueError:
            print "Value must be between 0.0 and 20.0"

    def set_width(self, width):
        self.__width = float(width)
        try:
            #self.__width = float(width)
            if self.__width > 0.0 and self.__width < 20.0:
                print "Value is in range.  You may continute."
            else:
                raise ValueError
        except ValueError:
            print "Value must be between 0.0 and 20.0"
##Getters
    def get_length(self):
        return self.__length

    def get_width(self):
        return self.__width

##Get perimeter and area
    def perimeter(self):
        return 2 * self.__length + 2 * self.__width

    def area(self):
        return self.__length * self.__width
import rectclass

def main():
    ## Get length and width

    print 'Enter numeric data greater than 0.0 but less than 20.0'
    print
    a_len = input('Enter Length: ')
    print
    wide = input('Enter Width: ')

    calculations = rectclass.Rectangle(a_len, wide)

    print calculations.perimeter()
    print
    print calculations.area()

main()

Dani AI

Generated

Good move by : calling the setters from init is what makes runtime validation actually run. The original symptom came from assigning raw values in init (and therefore bypassing the validation code). A couple of follow-ups will make the class more robust and easier to reuse:

  • Prefer properties instead of separate set_/get_ methods so validation lives in one place and the public API looks like normal attributes.
  • Don’t print validation messages from inside the class; raise a TypeError/ValueError so calling code can decide how to handle errors. Swallowing exceptions or only printing hides problems.
  • Convert to float inside the setter and explicitly catch conversion errors. Also watch Python version differences: in Python 2 input() evaluates expressions (use raw_input()), while in Python 3 input() returns a string you can float().

Example (Python 3, compact and explicit):

class Rectangle:
    def __init__(self, length=1.0, width=1.0):
        self.length = length
        self.width = width

    @property
    def length(self):
        return self._length

    @length.setter
    def length(self, val):
        try:
            v = float(val)
        except (TypeError, ValueError):
            raise TypeError("length must be a number")
        if not (0.0 < v < 20.0):
            raise ValueError("length must be >0.0 and <20.0")
        self._length = v

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, val):
        try:
            v = float(val)
        except (TypeError, ValueError):
            raise TypeError("width must be a number")
        if not (0.0 < v < 20.0):
            raise ValueError("width must be >0.0 and <20.0")
        self._width = v

    def perimeter(self):
        return 2 * (self._length + self._width)

    def area(self):
        return self._length * self._width

Final notes: avoid double-underscore names unless intentional (name-mangling), consider math.isfinite() to reject inf/nan, and add small unit tests to exercise invalid inputs (e.g., non-numeric, zero, negative, too large). These steps make the class predictable and easy to reuse in larger code.

Recommended Answers

All 3 Replies

What isn't working? It looks, at a glance, to be working.

Here it is. Now it works.

class Rectangle:

    def __init__(self, length = 1, width = 1):
        self.set_length(length)
        self.set_width(width)

    ##Setters to float
    def set_length(self, length):
        length = float(length)
        try:
            if 0.0 < length < 20.0:
                print "Value is in range.  You may continute."
                self._length = length
            else:
                raise ValueError
        except ValueError:
            print "Value must be between 0.0 and 20.0"

    def set_width(self, width):
        width = float(width)
        try:
            if 0.0 < width < 20.0:
                print "Value is in range.  You may continute."
                self._width = width
            else:
                raise ValueError
        except ValueError:
            print "Value must be between 0.0 and 20.0"
##Getters
    def get_length(self):
        return self._length

    def get_width(self):
        return self._width

##Get perimeter and area
    def perimeter(self):
        return 2 * self._length + 2 * self._width

    def area(self):
        return self._length * self._width

Cheers and Happy coding

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.