7. Exercises

  1. Fill out the main function below so that you handle two exceptions that may be raised by your call to some_function. If this function raises a ValueError, print “value error happening now”; if this function raises a UnicodeError, print “unicode error happening now”. Make sure your code can handle both errors. (Note: since some_function isn’t filled out, neither exception will be raised when you run the program.)

These next several problems are variations on a theme. Each will have you return a string that consists of a shape built out of # (hash) characters. It is left up to you to add the code you would need to run your functions (i.e., adding a main function and calling the respective function). These problems build in difficulty, and are examples in how solving smaller problems can lead you to incrementally build the solutions to larger problems.

  1. Write a function line(n) that returns a line with exactly n hashes.

    Example:

    print(line(5))

    Output:

    #####

  2. Write a function square(n) that returns an n by n square of hashes. Utilize your line function.

    Example:

    print(square(5))

    Output:

    #####
    #####
    #####
    #####
    #####
    
  3. Write a function rectangle(width, height) that returns a rectangle of the width and height given by the parameters. Again, utilize your line function to do this.

    Example:

    print(rectangle(5, 3))

    Output:

    #####
    #####
    #####
    
  4. Write a function stairs(n) that prints the pattern shown below, with height n. Again, utilize your line function to do this.

    Example:

    stairs(5))

    Output:

    #
    ##
    ###
    ####
    #####
    
  5. Write a function space_line(spaces, hashes) that returns a line with exactly the specified number of spaces, followed by the specified number of hashes.

    Example:

    print(space_line(3,5))

    Output:

    #This is where the edge is, so there's 3 spaces before hashes
       #####
    
  6. Write a function triangle(n) that returns an upright triangle of height n.

    Example:

    print(triangle(5))

    Output:

        #
       ###
      #####
     #######
    #########
    
  7. Write a function diamond(n) that returns a diamond where the triangle formed by the top portion has height n. Notice that this means the diamond has 2n - 1 rows.

    Example:

    diamond(5))

    Output:

        #
       ###
      #####
     #######
    #########
     #######
      #####
       ###
        #