# 如何编写函数,以及如何传递实参,让函数能够访问完成其工作所需
# 的信息;如何使用位置实参和关键字实参,以及如何接受任意数量的实参;显示输出的函数和返
# 回值的函数;如何将函数同列表、字典、if语句和while循环结合起来使用。你还知道了如何将
# 函数存储在被称为模块的独立文件中,让程序文件更简单、更易于理解。# 1 定义函数
def greet_user():"""显示hello"""print("hello world")
greet_user()# 2 向函数传递参数
def greet_user(username):"""显示简单的问候语"""print("Hello, " + username.title() + "!")
greet_user('jesse')print("")
# 默认值
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('black')
describe_pet('white','cat')# 3 返回值
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)print(" ")
# 传递任意数量的实参
# 形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封
# 装到这个元组中。
def make_pizza(*toppings):"""打印顾客点的所有配料"""print(toppings)make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')print("")
# 将函数存储在被称为模块的独立文件中,再将模块导
# 入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。
import pizza #import pizza让Python打开文件pizza.py
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')# 如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短
# 而独一无二的别名——函数的另一个名称,类似于外号
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
pazza.py
def make_pizza(size, *toppings):"""概述要制作的比萨"""print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")for topping in toppings:print("- " + topping)