# Solutions of suggested exercises -- Python review 1D
# Revised 2011 Sep 1 for Python 3 compatibility

# 1.  Formatting

def formatter ():
    print("%12d" % 1600)
    print("%.6f" % 1.5)
    print("%s+%s+%s" % ("cat", "chases", "dog"))

# 2.  Output to a file

def file_writer (filename):
    f = open(filename, "w")
    f.write("%12d\n" % 1600)
    f.write("%.6f\n" % 1.5)
    f.write("%s+%s+%s\n" % ("cat", "chases", "dog"))
    f.close()


# 3.  Read and process the file

def file_reader (filename):
    try:
        f = open(filename, "r")
        lines = f.readlines()
        if len(lines) == 3:
            i = int(lines[0])
            x = float(lines[1])
            n = len(lines[2].strip()) # remove flanking whitespace
            result = i + x + n
            print(result)
        else:
            print("Whoops!  Wrong number of lines in the file.")
    except IOError as e:        # Python 2: except IOError, e:
        print("Whoops!  There was an I/O problem.")
        print(e)
    except ValueError:
        print("Whoops!  One of these doesn't look like a number.")
        print(lines[0])
        print(lines[1])

        
