003. Python入门经典之二: 第四章演练函数和使用raise来处理异常

定义函数, 使用""""""为函数添加描述性说明, 使用__doc__打印函数说明:

#定义函数; Python的函数注释 使用 """"""
def in_fridge():
    """这是我的第一个Pythhon的函数, 同时也是在Python中第一次使用方法说明"""
    try:
        count = fridge[wanted_food]
    except KeyError:
        count=0
        """这也是我的方法说明"""
    return count;
#定义字典
fridge={"egg":8,"mushroom":20,"pepper":3,"cheese":2,"tomato":4,"milk":13}
#选择指定的主键
wanted_food="egg"
print ("%s price is %d $" % (wanted_food, in_fridge()))
#输出结果: egg price is 8 $

print ("我是函数in_fridge的说明:%s" % in_fridge.__doc__) #显示函数注释

print (dir())  #dir()方法显示函数的所有属性

#print(in_fridge.__defaults__)

fridge="Chilly Ice Makers"
print (fridge)
fridge={"egg":8,"mushroom":20,"pepper":3,"cheese":2,"tomato":4,"milk":13}
print ("%s" % fridge)

Persson = {"lucy":18, "tom":20, "tim":19}
def showName():
    """this is show Name"""
    Persson = {"lucy":18, "tom":20}
    return Persson;

print (showName())
print (Persson)
#运行结果:
'''{'lucy': 18, 'tom': 20}
{'tim': 19, 'lucy': 18, 'tom': 20}'''

 在Python中对函数使用参数和类型判断:

#在Python中对函数使用参数
def in_fridge(some_firdge, desired_item):
    """This is a fucntion to see if the fridge has food"""
    try:
        count=some_firdge[desired_item];
    except KeyError:
        count=0;
    return count;
Persson = {"lucy":18, "tom":20, "tim":19}
#调用带参数的函数
print (in_fridge(Persson,"lucy"))
print(in_fridge(Persson,"hi"))
#运行结果: 18            0
print(in_fridge({"egg":10,"apple":20,"orange":30},"egg"))
#运行结果: 10

#判断传入的参数的类型, 减少后期运行时不必要的麻烦, 比如上面的方法第一个参数我们期望的是得到一个字典, 但是用户可能
#会传入一个列表/字符串/对象等等, 此时Python会尽可能的去解释, 但是
#当后面用到字典的特性时,可能就会报错
#为了防止这种错误的发生, 尽可能的避免运行期的停止运行错误, 我们可以使用Type来判断
'''
def make_omelet(omelet_type):
    """这里传递一个字典, 这个字典中应该包含制作一个蛋卷的所有材料, 或者提供一个字符串类型的蛋卷"""
    if type(omelet_type) == type({}):
        print("传入与的是一个包含了制作蛋卷材料的字典")
        return make_food(omelet_type, "omelet")
    elif type(omelet_type) == type(""):
        omelet_ingredients = get_omelet_ingredients(omelet_type)
        return make_food(omelet_ingredients, omelet_type)
    else:
        print("I don't think I can make this kind of omelet: %s" % omelet_type)
#当然上面的方法还是不能运行的. 我这里就是敲出来看看
'''

#使用type函数确定更多的类型
fridge={"egg":10,"apple":20,"orange":30};
print (type(fridge))
#输出结果:<type 'dict'>
print (type({}))

print(type(""))
print (type("hello"))
#输出结果: <type 'str'>    <type 'str'>

#类型匹配
if str(type(fridge)) == "<type 'dict'>":
    print ("They match!!~~")

 为参数定义默认值:

#为参数定义默认值
def make_omelet(omelet_type="milk"):
    """这里传递一个字典, 这个字典中应该包含制作一个蛋卷的所有材料, 或者提供一个字符串类型的蛋卷"""
    if type(omelet_type) == type({}): #如果类型是字典
        print("传入与的是一个包含了制作蛋卷材料的字典")
        return make_food(omelet_type, "omelet")
    elif type(omelet_type) == type(""):#如果类型是字符串
        #在函数中调用其它函数
        omelet_ingredients = get_omelet_ingredients(omelet_type)
        return make_food(omelet_ingredients, omelet_type)
    else:
        print("我认为这个玩意不能做蛋卷: %s" % omelet_type)

#制作点断的所需的第一个函数
def get_omelet_ingredients(omelet_name):
    """包含制作蛋卷的材料"""
    # All of our omelets need eggs and milk
    ingredients = {"eggs":2, "milk":1,"cheddar":4}
    if omelet_name == "eggs":
       # print ("我是一个值 %s" % ingredients["cheddar"])
        ingredients["eggs"] = 3
        #print ("我是一个值 %s" % ingredients["cheddar"])
    elif omelet_name == "milk":
        ingredients["jack_cheese"] = 2
        ingredients["ham"]         = 1
        ingredients["pepper"]      = 1
        ingredients["onion"]       = 1
    elif omelet_name == "cheddar":
        ingredients["feta_cheese"] = 2
        ingredients["spinach"]     = 2
    else:
        print("That's not on the menu, sorry!")
        return None
    return ingredients

#制作蛋卷的第二个函数
def make_food(ingredients_needed, food_name):
    """制作蛋卷的第二个函数: 参数表示所需的材料和材料名字"""
    #print ("字典%s" % ingredients_needed)
    #print ("键%s" % food_name)
    for ingredient in ingredients_needed.keys():
        print("添加 %d 份 %s 来做一个 %s%s" % (ingredients_needed[ingredient],food_name, food_name ,"蛋卷"))
    print("制作 %s%s" % (food_name,"蛋卷"))
    return food_name

#调用函数
print(make_omelet("eggs"))

'''输出结果:
#字典{'eggs': 3, 'cheddar': 4, 'milk': 1}
#键eggs
添加 3 份 eggs 来做一个 eggs蛋卷
添加 4 份 eggs 来做一个 eggs蛋卷
添加 1 份 eggs 来做一个 eggs蛋卷
制作 eggs蛋卷
eggs'''

#使用raise...(加注/注解)表示错误, 此关键字和try: except:对应
#当使用raise...指出(捕获)错误的时候, 还可以使用except...来捕获并且显示出来(关于此错误的解释)
'''
def make_omelet(omelet_type="eggs"):
    def get_omelet_ingredients(omelet_name):
        ingredients = {"eggs":2, "milk":1}
        if omelet_name == "eggs":
            ingredients["eggs"] = 2
        elif omelet_name == "western":
            ingredients["jack_cheese"] = 2
    if type(omelet_type) == type({}):
        print("omelet_type is a dictionary with ingredients")
        return make_food(omelet_type, "eggs")
    elif type(omelet_type) == type(""):
        omelet_ingredients = get_omelet_ingredients(omelet_type)
        return make_food(omelet_ingredients, omelet_type)
    else:
        raise TypeError("No such omelet type: %s" % omelet_type)
print(make_omelet("eggss"))
'''

 习题和练习使用raise来处理异常

'''
def do_plus(num1, num2):
    """两个整数相加的函数"""
    return ("num1+num2=%d" % (num1+num2))

print ("第一个题: %s" % do_plus(2,3))
'''



def do_plus(num1, num2):
    """两个整数相加的函数"""
    try:
        if str(type(num1))=="<type 'int'>" and str(type(num2))=="<type 'int'>":
            sum = ("num1+num2=%d" % (num1+num2))
            return sum;
        else :
            raise
    except: #TypeError:
        return "请输入一个数字";

    '''
    elif str(type(num1))!="<type 'int'>":
        return "第一个数字输入有误!~~~"
    elif  str(type(num2))!="<type 'int'>":
        return "第二个数字输入有误!~~~"
    '''
#do_plus("a",3)
print ("第二个题: %s" % do_plus({},3))

 

posted on 2017-02-24 15:04  印子  阅读(152)  评论(0)    收藏  举报

导航