python函数基础【第四章】

#函数
def favorite_book(title):
    print("one of my favorite books is  " + title.title() +".\n")
favorite_book('Alice in Wonderland')
#关键字实参
def describle_pet(animal_type , pet_name):
    print("\nI have a " +animal_type + ".")
    print("my " + animal_type + "'s name is "+ pet_name.title() + ".")
describle_pet(animal_type = 'hamster', pet_name ="harry")
#默认值
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(pet_name = 'willie',animal_type = 'pig')
#返回值函数
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, age=' '):
    person = {'first ': first_name, 'last ': last_name}
    if age:
        person['age'] = age
    return person
musician = build_person('jimi', 'hendrix',age = 27)
print(musician)
#函数中传递列表和修改列表
unprinted_designs =['iphone case', 'robot pendant', 'dodecahedron']
completed_models =[]

while unprinted_designs:
    current_design = unprinted_designs.pop()
    print("printing model: " + current_design)
    completed_models.append(current_design)

print("\nThe following models have been printed: ")
for completed_model in  completed_models:
    print(completed_model)
#传递任意数量的实参 创建空元组
def make_pizza(*toppings):
    print(toppings)
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
user_profile = build_profile('albert', 'einstein',location ='princeton',field = 'physics')
print(user_profile)
#函数和模块的导入
'''import module_name    module_name.function_name()'''
'''from module_name import function_name'''
'''from module_name import function_0,function_1'''
#使用as给函数指定别名
'''from module_name import function_name as myname'''
#使用as给模块指定别名
'''import module_name  as name'''
#导入模块中的所有函数(再使用它的函数无需使用句点)
'''from module_name import* '''
实验结果:

============ RESTART: C:/Users/Administrator/Desktop/chapater4.py ============
one of my favorite books is  Alice In Wonderland.


I have a hamster.
my hamster's name is Harry.

I have a dog.
my dog's name is Willie.

I have a pig.
my pig's name is Willie.
Jimi Hendrix
{'first ': 'jimi', 'last ': 'hendrix', 'age': 27}
printing model: dodecahedron
printing model: robot pendant
printing model: iphone case

The following models have been printed: 
dodecahedron
robot pendant
iphone case
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

猜你喜欢

转载自blog.csdn.net/zjguilai/article/details/89313758