函数

一.定义函数

  1. def greet_user():
  2. """显示简单的问候语"""
  3. print("Hello!")
  4. greet_user()
  1. Hello!

1.向函数传递信息

  1. def greet_user(username):
  2. """显示简单的问候语"""
  3. print("Hello, " + username.title() + "!")
  4. greet_user('jesse')
  1. Hello, Jesse!

2.实参与形参

前面定义函数greet_user() 时,要求给变量username 指定一个值。调用这个函数并提供这种信息(人名)时,它将打印相应的问候语。在函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息。在代码greet_user(‘jesse’) 中,值’jesse’ 是一个实参。实参是调用函数时传递给函数的信息。我们调用函数时,将要让函数使用的信息放在括号内。在greet_user(‘jesse’) 中,将实参’jesse’ 传递给了函数greet_user() ,这个值被存储在形参username 中。

二.传递实参

1.位置实参

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  5. describe_pet('hamster', 'harry')
  1. I have a hamster.
  2. My hamster's name is Harry.

2.关键字实参

  1. def describe_pet(animal_type, pet_name):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  5. describe_pet(animal_type='hamster', pet_name='harry')

关键字实参的顺序无关紧要,因为Python知道各个值该存储到哪个形参中。下面两个函数调用是等效的:

  1. describe_pet(animal_type='hamster', pet_name='harry')
  2. describe_pet(pet_name='harry', animal_type='hamster')

3.默认值

  1. def describe_pet(pet_name, animal_type='dog'):
  2. """显示宠物的信息"""
  3. print("\nI have a " + animal_type + ".")
  4. print("My " + animal_type + "'s name is " + pet_name.title() + ".")
  5. describe_pet(pet_name='willie')
  1. I have a dog.
  2. My dog's name is Willie.

三.返回值

1.返回简单值

  1. def get_formatted_name(first_name, last_name):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + last_name
  4. return full_name.title()
  5. musician = get_formatted_name('jimi', 'hendrix')
  6. print(musician)
  1. Jimi Hendrix

2.让实参变成可选的

  1. def get_formatted_name(first_name, middle_name, last_name):
  2. """返回整洁的姓名"""
  3. full_name = first_name + ' ' + middle_name + ' ' + last_name
  4. return full_name.title()
  5. musician = get_formatted_name('john', 'lee', 'hooker')
  6. print(musician)
  1. John Lee Hooker
  1. def get_formatted_name(first_name, last_name, middle_name=''):
  2. """返回整洁的姓名"""
  3. if middle_name:
  4. full_name = first_name + ' ' + middle_name + ' ' + last_name
  5. else:
  6. full_name = first_name + ' ' + last_name
  7. return full_name.title()
  8. musician = get_formatted_name('jimi', 'hendrix')
  9. print(musician)
  10. musician = get_formatted_name('john', 'hooker', 'lee')
  11. print(musician)
  1. Jimi Hendrix
  2. John Lee Hooker

四.传递任意数量的实参

  1. def make_pizza(*toppings):
  2. """打印顾客点的所有配料"""
  3. print(toppings)
  4. make_pizza('pepperoni')
  5. make_pizza('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings 中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。函数体内的print 语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此:

  1. ('pepperoni',)
  2. ('mushrooms', 'green peppers', 'extra cheese')
  1. def make_pizza(*toppings):
  2. """概述要制作的比萨"""
  3. print("\nMaking a pizza with the following toppings:")
  4. for topping in toppings:
  5. print("- " + topping)
  6. make_pizza('pepperoni')
  7. make_pizza('mushrooms', 'green peppers', 'extra cheese')
  1. Making a pizza with the following toppings:
  2. - pepperoni
  3. Making a pizza with the following toppings:
  4. - mushrooms
  5. - green peppers
  6. - extra cheese

1.使用任意数量的关键字实参

  1. def build_profile(first, last, **user_info):
  2. """创建一个字典,其中包含我们知道的有关用户的一切"""
  3. profile = {}
  4. profile['first_name'] = first
  5. profile['last_name'] = last
  6. for key, value in user_info.items():
  7. profile[key] = value
  8. return profile
  9. user_profile = build_profile('albert', 'einstein',
  10. location='princeton',
  11. field='physics')
  12. print(user_profile)
  1. {'first_name': 'albert', 'last_name': 'einstein',
  2. 'location': 'princeton', 'field': 'physics'}

五.将函数储存在模块中

1.导入整个模块

  1. def make_pizza(size, *toppings):
  2. """概述要制作的比萨"""
  3. print("\nMaking a " + str(size) +
  4. "-inch pizza with the following toppings:")
  5. for topping in toppings:
  6. print("- " + topping)

接下来,我们在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza() 两次:

  1. import pizza
  2. pizza.make_pizza(16, 'pepperoni')
  3. pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

2.导入特定的函数

  1. from module_name import function_name

**通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数

  1. from module_name import function_0, function_1, function_2

3.使用as给函数指定别名

  1. from pizza import make_pizza as mp
  2. mp(16, 'pepperoni')
  3. mp(12, 'mushrooms', 'green peppers', 'extra cheese')

4.使用as给模块指定别名

  1. import pizza as p
  2. p.make_pizza(16, 'pepperoni')
  3. p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

5.导入模块中的所有函数

  1. from pizza import *
  2. make_pizza(16, 'pepperoni')
  3. make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Lambda 表达式

Lambda函数又叫匿名函数

  1. 1、单个参数的:
  2. >>> g = lambda x : x ** 2
  3. >>> print g(3)
  4. 9
  5. 2、多个参数的:
  6. >>> g = lambda x, y, z : (x + y) ** z
  7. >>> print g(1,2,2)
  8. 9
  1. #测试lambda函数
  2. f=lambda a,b,c,d:a*b*c*d
  3. print(f(1,2,3,4)) #相当于下面这个函数
  4. def test01(a,b,c,d):
  5. return a*b*c*d
  6. print(test01(1,2,3,4))
  7. g=[lambda a:a*2,lambda b:b*3]
  8. print(g[0](5)) #调用
  9. print(g[1](6))