python学习之路(七)-函数

学习来源于《Python编程:从入门到实践》,感谢本书的作者和翻译工作者。

下面为学习笔记

# 在这里,函数名为greet_user(),它不需要任何信息就能完成其工作,因此括号是空
# 的(即便如此,括号也必不可少)。最后,定义以冒号结尾。
def greet_user():
# """显示简单的问候语"""
    print("Hello!")
greet_user()
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')
describe_pet('dog', 'willie')
# 关键字实参是传递给函数的名称—值对。你直接在实参中将名称和值关联起来了,因此向函
# 数传递实参时不会混淆(不会得到名为Hamster的harry这样的结果)。
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(pet_name='harry', animal_type='hamster')
# 编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时, Python将使用
# 指定的实参值;否则,将使用形参的默认值。
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')
# 一条名为Willie的小狗
describe_pet('willie')
describe_pet(pet_name='willie')
# 一只名为Harry的仓鼠
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')
# 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。
def get_formatted_name(first_name, last_name):
# """返回整洁的姓名"""
    full_name = first_name + ' ' + last_name
    return full_name.title()
musician1 = get_formatted_name('jimi', 'hendrix')
print(musician1)
def build_person(first_name, last_name, age=''):
# """返回一个字典,其中包含有关一个人的信息"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age
    return person
musician = build_person('jimi', 'hendrix', age='27')#age 是字符串
print(musician)
def greet_users(names):
# """向列表中的每位用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

def print_models(unprinted_designs, completed_models):
# """
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
# """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
# 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
def show_completed_models(completed_models):
# """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    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)
# 切片表示法[:]创建列表的副本。在print_models中,如果不想清空未打印的设计列表,
# 可像下面这样调用print_models(): print_models(unprinted_designs[:], completed_models)
def make_pizza(*toppings):#形参名*toppings中的星号让Python创建一个名为toppings的空元组
# """打印顾客点的所有配料"""
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
# 下面的函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们统统收入囊中
def build_profile(first, last, **user_info):#形参**user_info中的两个星号让Python创建一个名为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)
# 要让函数是可导入的,得先创建模块。 模块是扩展名为.py的文件,包含要导入到程序中的代码。
# 你还可以导入模块中的特定函数,这种导入方法的语法如下:
# from module_name(模块名称) import function_name(函数名称)
# 通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:
# from module_name import function_0, function_1, function_2

# 如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短
# 而独一无二的别名——函数的另一个名称,类似于外号。要给函数指定这种特殊外号,需要在导
# 入它时这样做。关键字as将函数重命名为你提供的别名:
# 例如:from pizza import make_pizza as mp (mp就是提供的别名)
# 你还可以给模块指定别名。通过给模块指定简短的别名(如给模块pizza指定别名p),让你
# 能够更轻松地调用模块中的函数。例如: import pizza as p
# 相比于pizza.make_pizza(), p.make_pizza()更为简洁:

# 使用星号( *)运算符可让Python导入模块中的所有函数:
# from pizza import *

猜你喜欢

转载自blog.csdn.net/mugong11/article/details/81233690