Libraries and Modules in Python

Solutions

In [12]:
class Person:
    """Class that holds a person's height"""
    def __init__(self, height=0, weight=0):
        """Construct a person with the specified name, height and weight"""
        self.setHeight(height)
        self.setWeight(weight)
    def setHeight(self, height):
        """Set the person's height in meters"""
        try:
            height = float(height)
        except:
            height = string_to_height(height)
        if height < 0 or height > 2.5:
            raise ValueError("Invalid height: %s. This shoud be between 0 and 2.5 meters" % height)
        self._height = height
    def setWeight(self, weight):
        """Set the person's weight in kilograms"""
        if weight < 0 or weight > 500:
            raise ValueError("Invalid weight: %s. This should be between 0 and 500 kilograms" % weight)
        self._weight = weight
    def getHeight(self):
        """Return the person's height in meters"""
        return self._height
    def getWeight(self):
        """Return the person's weight in kilograms"""
        return self._weight
    def bmi(self):
        """Return the person's body mass index (bmi)"""
        if (self.getHeight() == 0 or self.getWeight() == 0):
            raise NullPersonError("Cannot calculate the BMI of a person with zero "
                                  "height or weight (%s,%s)" % (self.getHeight(),self.getWeight()))
        return self.getWeight() / self.getHeight()**2
In [13]:
p = Person(height="cat", weight=20)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-12-a83ea0f0b594> in setHeight(self, height)
     10         try:
---> 11             height = float(height)
     12         except:
ValueError: could not convert string to float: 'cat'
During handling of the above exception, another exception occurred:
TypeError                                 Traceback (most recent call last)
<ipython-input-13-2b20e23399be> in <module>
----> 1 p = Person(height="cat", weight=20)
<ipython-input-12-a83ea0f0b594> in __init__(self, height, weight)
      3     def __init__(self, height=0, weight=0):
      4         """Construct a person with the specified name, height and weight"""
----> 5         self.setHeight(height)
      6         self.setWeight(weight)
      7 
<ipython-input-12-a83ea0f0b594> in setHeight(self, height)
     11             height = float(height)
     12         except:
---> 13             height = string_to_height(height)
     14 
     15         if height < 0 or height > 2.5:
<ipython-input-8-dc5d35b21621> in string_to_height(height)
     17 
     18     # Getting here means that we haven't been able to extract a valid height
---> 19     raise TypeError("Cannot extract a valid height from '%s'" % height)
TypeError: Cannot extract a valid height from 'cat'

In [14]:
def string_to_weight(weight):
    """This function tries to interpret the passed argument as a weight 
       in kilograms. The format should be 'X kg' 'X kilogram' or 'X kilograms',
       where 'X' is a number
    """
    # convert weight to a string - this always works
    weight = str(weight)
    words = weight.split(" ")
    if len(words) == 2:
        if words[1] == "kg" or words[1] == "kilogram" or words[1] == "kilograms" \
            or words[1] == "kilo" or words[1] == "kilos":
            try:
                return float(words[0])
            except:
                pass
    # Getting here means that we haven't been able to extract a valid weight
    raise TypeError("Cannot extract a valid weight from '%s'" % weight)
In [15]:
class Person:
    """Class that holds a person's height"""
    def __init__(self, height=0, weight=0):
        """Construct a person with the specified name, height and weight"""
        self.setHeight(height)
        self.setWeight(weight)
    def setHeight(self, height):
        """Set the person's height in meters"""
        try:
            height = float(height)
        except:
            height = string_to_height(height)
        if height < 0 or height > 2.5:
            raise ValueError("Invalid height: %s. This shoud be between 0 and 2.5 meters" % height)
        self._height = height
    def setWeight(self, weight):
        """Set the person's weight in kilograms"""
        try:
            weight = float(weight)
        except:
            weight = string_to_weight(weight)
        if weight < 0 or weight > 500:
            raise ValueError("Invalid weight: %s. This should be between 0 and 500 kilograms" % weight)
        self._weight = weight
    def getHeight(self):
        """Return the person's height in meters"""
        return self._height
    def getWeight(self):
        """Return the person's weight in kilograms"""
        return self._weight
    def bmi(self):
        """Return the person's body mass index (bmi)"""
        if (self.getHeight() == 0 or self.getWeight() == 0):
            raise NullPersonError("Cannot calculate the BMI of a person with zero "
                                  "height or weight (%s,%s)" % (self.getHeight(),self.getWeight()))
        return self.getWeight() / self.getHeight()**2
In [16]:
p = Person(weight="55.6 kilos", height="1.5 meters")