Homework Solution

Error Checking and Exceptions

Problems to be Submitted (20 points)

  1. (10 points)

    Write a program that asks a user for a weight in pounds (possibly fractional), and outputs the weight in kilograms. (For the record, 1 pound equals approximately 0.45359 kilograms.)

    lbs = -1
    while lbs < 0:
        try:
            lbs = float(input('Enter a weight in pounds: '))
            if lbs < 0:
                print('Weights must be nonnegative.')
        except ValueError:
            print('That is not a valid number.')
    
    kg = 0.45359 * lbs
    print('That is equal to', kg, 'kilograms.')

  2. (10 points)

    Assume that we are writing a function doSomething(word, k) which expects that parameter word is a nonempty string, and that parameter k is a nonnegative intger that has value no greater than the length of the given word.

    Give an implementation of such a function that rigorously checks that the parameters adhere to these expectations. (Once you've performed the parameter-checking, you don't need to do anything within the function body.)

    def doSomething(word, k):
        if not isinstance(word, str):
            raise TypeError('word must be a string')
        if len(word) == 0:
            raise ValueError('word must be nonempty')
        if not isinstance(k, int):
            raise TypeError('k must be an integer')
        if k < 0:
            raise ValueError('k must be nonnegative')
        if k > len(word):
            raise ValueError('k must be no greater than the length of the word')
    


Last modified: Thursday, 18 October 2018