Tuesday, October 8, 2013

Second Post 9/30 Raise and Exception

9/30 Raise and Exception
In last week, I learned how to raise errors for different situations with exceptions which is very interesting and helpful.
There are some errors that appear frequently before when I running my codes.
For example:
name error,

>>>hello
NameError: name "hello" is not defined

syntax error,

def function()
SyntaxError: invalid syntax

index error,

>>>list = [1, 2, 3]
>>>list[4]
IndexError: list index out of range

input error,
>>>f = open("x.txt","r")
IOError: No such file or directory: "x.txt"

......

After lectures of this week, I can raise my own designed error base on the situation.
Keywords are: raise, try, except


1.
def raiser(x):
    if x == "So sue me!":
        raise E2Exception("New Yorker")

When the input x is exactly the same as "So sue me!" it raise an exception named E2Exception which is a subclass of Exception(I will mention subclass later in this post).


from e2a import raiser, E2Exception, E2OddException


2.
def reporter(raiser, x):
    try:
        raiser(x)
    except ValueError as v:
        return "Value"




First Post 9/25: Hard Coded

9/25: Hard Coded
From exercise 1 I learned how to call a function inside a definition
First you need to call the class name. Afterwards attach the function name to class name, followed by(). For example,


class Toy(object):
    def play(self):
        print ("Squeak!")
class Dog(object):
   
    def __init__(self, name):
        self.name = name
       
    def play(self,  toy, n):
        if n < 0:
            n = 0
        for i in range(n):
print( “Yip! ”, end=’’)
toy.play()

When the dog playing the toy, he speaks base on the toy he plays with. Therefore, I want the output from class Toy, which is “Squeak!”. However if I just print(self.speak Squeak!) this is a hard-coded.

Hard coding is simply embedding input data directly into the code of a program instead of getting the data from an external source. That means the data inputed cannot be change. If we give the dog another toy he can't speaks anything different. Hence we need to call toy.play() under dog.play() function.