函数
定义函数
def greet_user():
"""显示简单的问候语"""
print("hello")
参数
向函数传递信息
def greet_user(username):
"""显示简单的问候语"""
print("hello , " + username)
关键字实参
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print("宠物类型: " + animal_type)
print("宠物姓名: " + pet_name)
describe_pet(animal_type='hamster', pet_name='harry')
关键字实参的顺序无关紧要。
默认值
编写函数时,可给每个形参指定默认值。在调用函数时给形参提供了实参时,Python将使用指定的实参值;否则,将使用形参的默认值。因此,给形参默认值后,可在函数调用中省略相应的实参。使用默认值可简化函数调用,还可清楚的指出函数的典型用法。
返回值
返回简单值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
返回字典
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
def build_person(first_name, last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
return person
传递列表
def greet_users(names):
"""向列表中每位用户发出问候"""
for name in names:
msg = "Hello, " + name.title() + '.'
print(msg)
在函数中修改列表
def print_models(unprinted_designs, completed_models):
"""打完每个设计,并将其移到completed_models"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print("打印模型: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
"""显示打印好的所有模型"""
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
禁止函数修改列表
有时候需要禁止函数修改列表。可是将列表的副本传递给函数,像这样:
function_name(list_name[:])
传递任意数量的实参
有时候,无法预先知道函数需要接受多少个实参。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
形参名*toppings
中的星号让Python创建一个名为topping
的空元组,并将收到的所有值都封装到这个元组中。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
for topping in toppings:
print('-' + topping)
make_pizza('pepperoni')
make_pizza('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
网友评论