您的位置:首页 > 编程语言 > Python开发

Python学习之函数

2017-10-24 23:50 134 查看
    函数这章的学习效率比较低。
#定义函数
def greet_user(username):
"""显示简单的问候语"""
print("Hello, "  + username .title()+ "!")
greet_user('jesse')
"""username是个形参,jesse是实参,它被存储在形参username中"""

#位置实参传递
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')

#关键字实参
"""关键字实参的顺序无关紧要,使用时的形参名一定要准确"""
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')

#默认值
"""使用默认值时在形参列表中必须先列出没有默认值的形参,
在列出有默认值的形参以便能够正确解读位置实参"""
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')

#等效实参
def describe_pet(pet_name,animal_type = 'dog'):
print("\nMy " + animal_type + "'s name is " + pet_name.title() + "!")
describe_pet('willie')
describe_pet(pet_name = 'willie')
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,middle_name = ''):
"""返回完整的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' +last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print("\n" + musician)
musician = get_formatted_name('jahn','hooker','lee')
print("\n" + 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)

#传递列表
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah','ty','margot']
greet_users(usernames)

#传递任意数量的实参结合使用位置实参
def make_pizza(size,*toppings):
"""*toppings是创建一个名为toppings的空元组,所接受到的值都封装到元组中"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
"""一般是位置实参和关键字实参先匹配,因此将接受任意数量实参的形参放在最后"""

#使用任意数量的关键字参数
"""**user_info表示创建一个名为user_info的空字典并将所有收到的名称值都封装到这个字典中"""
def build_profile(first,last,**user_info):
profile = {}
profile['firstname'] = first
profile['lastname'] = 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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: