Chapter 08:函数

定义函数

def greet_user(name):
    print("Hello, " + name.title() + '!')
    
greet_user('jesse')

Hello, Jesse!

关键字实参使得实参的传递不必严格按照形参的顺序

def describe_pet(animal_type, pet_name):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet(animal_type='hamster', pet_name='harry')

I have a hamster.
My hamster's name is Harry.

带默认值的形参,显然有默认值的形参在参数列表中排在无默认值形参的后面

def describe_pet(pet_name, animal_type='dog'):
    print("I have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

describe_pet('harry')

I have a dog.
My dog's name is Harry.

简单返回值的函数

def get_formmatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()

print(get_formmatted_name('jimi','hendrix'))

Jimi Hendrix

函数可返回任何类型的值,包括列表和字典

def build_person(first_name,last_name,age=''):
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person

musician = build_person('jimi','hendrix',age=27)
print(musician)

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

传递列表并修改

def greet_users(names):
    for i in range(len(names)):
        names[i] = names[i].title()
        
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
print(usernames)

['Hannah', 'Ty', 'Margot']

当不打算改变原列表时,可传入列表的副本

def greet_users(names):
    for i in range(len(names)):
        names[i] = names[i].title()
        
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames[:])
print(usernames)

['hannah', 'ty', 'margot']

传递任意数量的实参

def make_pizza(*toppings): #toppings 是一个元组
    for topping in toppings:
        print(topping)
    
make_pizza('pepperoni')
make_pizza('mushroooms','green peppers','extra cheese')

pepperoni
mushroooms
green peppers
extra cheese

结合使用位置实参和任意数量实参

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

使用任意数量的关键字实参,很多库的API都这么设计

def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile1 = build_profile('albert','einstein',
                            location='princton',field='physics')
user_profile2 = build_profile('marie','curie',
                              user_info={'location':'paris','field':'pthsics'})
#不能这么写
#user_profile2 = build_profile('marie','curie',
#                              {'location':'paris','field':'pthsics'})
u3info = {'location': 'london','field': 'computer'}
user_profile3 = build_profile('turing','alen',**u3info)

print(user_profile1)
print(user_profile2)
print(user_profile3)

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princton', 'field': 'physics'}
{'first_name': 'marie', 'last_name': 'curie', 'user_info': {'location': 'paris', 'field': 'pthsics'}}
{'first_name': 'turing', 'last_name': 'alen', 'location': 'london', 'field': 'computer'}

将函数存储为单独的模块

将pizza.py与making_pizzas.py置于同一目录

pizza.py内容

def make_pizza(size, *toppings):
    print("\nMaking a "+str(size) + '-inch pizza with the following toppings:')
    for topping in toppings:
        print('-' + topping)

making_pizzas.py 通过 import 导入 pizza 模块

import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')

导入特定的函数

from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')

使用as给函数指定别名

from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green pepers', 'extra cheese')

as也可以给模块起别名

import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green pepers', 'extra cheese')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • emmm,这部分学的很累,也花了很长时间,但是工欲善其事必先利其器,基础是必不可少的。Python的语法相对来说比...
    马小野阅读 5,153评论 0 37
  • 1、传递实参 1.1 位置实参 def describe_pet(animal_type,pet_name): p...
    梦vctor阅读 329评论 0 0
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,919评论 0 38
  • 来祖国的最南端已有整整一年,来的越久,越是想念北方,那些四季分明的春夏秋冬,那些穿着羽绒服雪地靴去踩雪的日子,...
    Juliet_超阅读 375评论 0 0
  • 昨晚设置了闹铃,今天早上七点就准时起床了,因为昨天和朋友门约好今天早上十点出发去五老山遛狗,大家一起游玩一天!因为...
    FAB至尚陈小猪阅读 132评论 0 0