פתרונות פרק 33 קורס פייתון

תרגיל 1:

"""
Write a program that asks the user to enter numbers in a loop
and prints the square root of each number. Warn if value is not valid
Program should finish when End-Of-Input character is entered.
"""

from __future__ import print_function
import sys
import math

for line in iter(sys.stdin.readline, ''):
    try:
        number = int(line)
        print("Sqrt({}) = {}".format(number, math.sqrt(number)))

    except ValueError:
        print("Invalid value: {}".format(line.strip()))

תרגיל 2

"""
Write a program that takes a file name and prints the number of lines in that file
Print a friendly error if file not found

python ex2.py /etc/shells
11

python ex2.py /foo/bar
Sorry, file /foo/bar not found
"""

import sys
try:
    fname = sys.argv[1]
    count = 0
    with open(fname) as f:
        for line in f:
            count += 1
    print("File {} has {} lines".format(fname, count))

except IndexError:
    print("Missing file name")
except IOError:
    print("File not found: {}".format(sys.argv[1]))

תרגיל 3

"""
The following code assumes a class named ImageFile exists
and represents an image.

Write that class so all tests pass
"""

class InvalidImageExt(Exception):
    pass

class ImageFile:
    def __init__(self, name):
        if not any(name.endswith(ext) for ext in ['.png', '.jpg', '.gif']):
            raise InvalidImageExt()

import unittest

class TestImageFile(unittest.TestCase):
    def test_good_ext(self):
        try:
            img = ImageFile("file.png")
        except InvalidImageExt:
            self.fail("png should be a valid file extension")

    def test_bad_ext(self):
        with self.assertRaises(InvalidImageExt):
            img = ImageFile("file.mp3")

unittest.main()