函数
一.定义函数
def greet_user():"""显示简单的问候语"""print("Hello!")greet_user()
Hello!
1.向函数传递信息
def greet_user(username):"""显示简单的问候语"""print("Hello, " + username.title() + "!")greet_user('jesse')
Hello, Jesse!
2.实参与形参
前面定义函数greet_user() 时,要求给变量username 指定一个值。调用这个函数并提供这种信息(人名)时,它将打印相应的问候语。在函数greet_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息。在代码greet_user(‘jesse’) 中,值’jesse’ 是一个实参。实参是调用函数时传递给函数的信息。我们调用函数时,将要让函数使用的信息放在括号内。在greet_user(‘jesse’) 中,将实参’jesse’ 传递给了函数greet_user() ,这个值被存储在形参username 中。
二.传递实参
1.位置实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet('hamster', 'harry')
I have a hamster.My hamster's name is Harry.
2.关键字实参
def describe_pet(animal_type, pet_name):"""显示宠物的信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet(animal_type='hamster', pet_name='harry')
关键字实参的顺序无关紧要,因为Python知道各个值该存储到哪个形参中。下面两个函数调用是等效的:
describe_pet(animal_type='hamster', pet_name='harry')describe_pet(pet_name='harry', animal_type='hamster')
3.默认值
def describe_pet(pet_name, animal_type='dog'):"""显示宠物的信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet(pet_name='willie')
I have a dog.My dog's name is Willie.
三.返回值
1.返回简单值
def get_formatted_name(first_name, last_name):"""返回整洁的姓名"""full_name = first_name + ' ' + last_namereturn full_name.title()musician = get_formatted_name('jimi', 'hendrix')print(musician)
Jimi Hendrix
2.让实参变成可选的
def get_formatted_name(first_name, middle_name, last_name):"""返回整洁的姓名"""full_name = first_name + ' ' + middle_name + ' ' + last_namereturn full_name.title()musician = get_formatted_name('john', 'lee', 'hooker')print(musician)
John Lee Hooker
def get_formatted_name(first_name, last_name, middle_name=''):"""返回整洁的姓名"""if middle_name:full_name = first_name + ' ' + middle_name + ' ' + last_nameelse:full_name = first_name + ' ' + last_namereturn full_name.title()musician = get_formatted_name('jimi', 'hendrix')print(musician)musician = get_formatted_name('john', 'hooker', 'lee')print(musician)
Jimi HendrixJohn Lee Hooker
四.传递任意数量的实参
def make_pizza(*toppings):"""打印顾客点的所有配料"""print(toppings)make_pizza('pepperoni')make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings 中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。函数体内的print 语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此:
('pepperoni',)('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):"""概述要制作的比萨"""print("\nMaking a pizza with the following toppings:")for topping in toppings:print("- " + topping)make_pizza('pepperoni')make_pizza('mushrooms', 'green peppers', 'extra cheese')
Making a pizza with the following toppings:- pepperoniMaking a pizza with the following toppings:- mushrooms- green peppers- extra cheese
1.使用任意数量的关键字实参
def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key, value in user_info.items():profile[key] = valuereturn profileuser_profile = build_profile('albert', 'einstein',location='princeton',field='physics')print(user_profile)
{'first_name': 'albert', 'last_name': 'einstein','location': 'princeton', 'field': 'physics'}
五.将函数储存在模块中
1.导入整个模块
def make_pizza(size, *toppings):"""概述要制作的比萨"""print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")for topping in toppings:print("- " + topping)
接下来,我们在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza() 两次:
import pizzapizza.make_pizza(16, 'pepperoni')pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
2.导入特定的函数
from module_name import function_name
**通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数
from module_name import function_0, function_1, function_2
3.使用as给函数指定别名
from pizza import make_pizza as mpmp(16, 'pepperoni')mp(12, 'mushrooms', 'green peppers', 'extra cheese')
4.使用as给模块指定别名
import pizza as pp.make_pizza(16, 'pepperoni')p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
5.导入模块中的所有函数
from pizza import *make_pizza(16, 'pepperoni')make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Lambda 表达式
Lambda函数又叫匿名函数
1、单个参数的:>>> g = lambda x : x ** 2>>> print g(3)92、多个参数的:>>> g = lambda x, y, z : (x + y) ** z>>> print g(1,2,2)9
#测试lambda函数f=lambda a,b,c,d:a*b*c*dprint(f(1,2,3,4)) #相当于下面这个函数def test01(a,b,c,d):return a*b*c*dprint(test01(1,2,3,4))g=[lambda a:a*2,lambda b:b*3]print(g[0](5)) #调用print(g[1](6))
