第8章 函数

使用def定义函数
def greet_user(username):
"""显示简单的问候语"""#文档字符串,描述了函数是用来做什么的
Python使用它们来生成有关程序中函数的文档
print("Hello, " + username.title() + "!")

greet_user('jesse')

位置实参/关键字实参:和R的用法一样
默认值

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')
describe_pet('Harry','hamster')

返回值,用return,和R的用法一样
让实参变成可选的:将可选的实参放在参数列表最后,并为其设置默认值
在函数体中检查其是否是默认值

Python把空字符串/非空列表解释为TRUE

在函数中修改列表,引起的变化是永久性的

禁止函数修改列表的方法:传递副本
function_name(list_name[:])

传递任意数量的实参

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

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

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_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)

输出
{'first_name': 'albert', 'last_name': 'einstein',
'location': 'princeton', 'field': 'physics'}

将函数存储在模块中
通过将函数存储在独立的文件中,可以隐藏程序代码的细节
将重点放在程序的高层逻辑上,并且可以便于在众多不同的程序中重用函数
将函数存储在独立文件中后,可以与其他程序员共享这些文件为不是整个程序
知道如何导入函数还可以便于使用其他程序员编写的函数库

import pizza
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

导入特定的函数
from module_name import function_0, function_1, function_2
使用这种语法,调用函数时无需使用句点
给模块函数指定别名
import module_name as mn
from module_name import function_name as fn
导入所有函数
from module_name import *

你可能感兴趣的:(第8章 函数)