函数
8.1 定义函数
def great_user():
print(“Hello!”)
great_user()
8.1.1 向函数传递信息
def great_user(username):
print("Hello, " + username.title() + “!”)
great_user(‘jesse’)
Hello, jesse!
8.1.2 实参和形参
username是一个形参,'jesse’是一个实参。
8.2 传递实参
8.2.1 位置实参
基于实参位置传递的关联方式称为位置实参
8.2.2 关键字实参
关键字实参是传递给函数的名称-值对。
describe_pet(animal_type = ‘hamster’,pet_name = ‘harry’)
8.2.3 默认值
def describe_pet(pet_name,animal_type = ‘harry’)
8.2.4 等效函数的调用
8.3 返回值
可使用return语句将值返回到调用函数的代码行
return full_name.title()
8.4 传递列表
def great_users(names):
for name in names:
msg = "Hello, " + name.title() + “!”
print(msg)
usernames = [‘hannah’,‘ty’,‘margot’]
great_users(usernames)
8.5 传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza(‘pepperoni’)
make_pizza(‘mushroom’,‘green peppers’,‘extra cheese’)
形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中,即使收到一个值也如此。
8.5.1 结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):
print()
make_pizza(15,‘pepperoni’)
make_pizza(12,‘mushroom’,‘green peppers’,‘extra cheese’)
8.5.2 使用任意数量的关键字实参
有时,需要接收任意数量实参,但预先不知道传递给函数的会是什么样的信息。这种情况下,可以将函数编写成能够接受任意数量的键-值对。
def build_profile(first,last,**user_info):
profile = {}
profile[‘first_name’] = first
profile[‘last_name’]= last
for key,value in user_info.items():
profiel[key] = value
return profile
user_profile = build_profile(‘albert’,‘einstein’,
location = ‘princeton’,
field = ‘physics’)
print(user_profile)
8.6 将函数存储在模块中
import语句允许在当前运行的程序文件中使用模块中的代码
import name
from module_name import function_name
8.6.3 使用as给函数指定别名
from pizza import make_pizza as mp
8.6.4 使用as给模块指定别名
import pizza as p
8.6.5 倒入模块中的所有函数
使用星号(*)运算符可让Python倒入模块中的所有函数:
from pizza import *
8.7 函数编写指南
给形参指定默认值时,等号两边不要有空格。
所有的import都应放在文件开头