函数

#定义函数
def greet_user():
    """显示简单的问候语"""
    print("Hello !")
greet_user()
>>>Hello !

#向函数传递信息
def greet_user(username):     #username是形参
    """简单的问候语"""
    print('Hello,%s !'% username.title())
greet_user('jacky')       #'jacky'是实参
>>>Hello,Jacky !

#位置实参
def describe_pet(animal_type,pet_name):
    print('\nI have a %s.' % animal_type)
    print('My %s\'s name is %s.' % (animal_type,pet_name.title()))
describe_pet('hamster','harry')
describe_pet('dog','willie')

#关键字实参
def describe_pet(animal_type,pet_name):
    print('\nI have a %s.' % animal_type)
    print('My %s\'s name is %s.' % (animal_type,pet_name.title()))
describe_pet(pet_name='alex',animal_type='dog')


#形参默认值
def describe_pet(pet_name,animal_type='dog'):
    print('\nI have a %s.' % animal_type)
    print('My %s\'s name is %s.' % (animal_type,pet_name.title()))
describe_pet(pet_name='alex')


# 编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如Reykjavik is in
# Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。

def describe_city(city,country):
    print('%s is in %s.' % (city.title(),country.title()))
describe_city('shanghai','chian')
>>>Shanghai is in Chian.

def describe_city(city,country='chian'):
    print('%s is in %s.' % (city.title(),country.title()))
describe_city('beijin')
>>>Beijin is in Chian.


#返回值

def get_formatted_name(first_name,last_name):
    """返回整洁的姓名"""
    full_name = ('%s %s' % (first_name,last_name))
    return full_name.title()
name = get_formatted_name('jacky','zhao')
print(name)

#让实参变成可选的
def get_formatted_name(first_name,last_name,meddle_name=''):    #不是所有人名都有中间名,所以需要给中间名添加默认值
    if meddle_name:     #Python将非空字符串解读为True ,因此如果函数调用中提供了中间名,if middle_name 将为True
        full_name = ('%s %s %s' % (first_name,meddle_name,last_name))
    else:   #如果没有提供中间名,middle_name 将为空字符串,导致if 测试未通过,进而执行else 代码块
        full_name = ('%s %s' % (first_name,last_name))
    return full_name.title()
name = get_formatted_name('jacky','zhao')
print(name)


#返回字典
def build_person(first_name,last_name):
    person = {'first':first_name.title(),'last':last_name.title()}
    return person
name = build_person('jacky','zhao')
print(name)


def build_person(first_name,last_name,age='',meddle_name=''):
    person = {'first':first_name.title(),'last':last_name.title()}
    if age:
        person['age'] = age
    return person
name = build_person('jacky','zhao',age = 30)
print(name)


# 结合使用函数和while 循环
def get_formatted_name(first_name,last_name):
    full_name = '%s %s' % (first_name,last_name)
    return full_name.title()
key = True
while key:
    print('\nPlease tell your name:')
    f_name = input('First_name=')
    l_name = input('Last_name=')
    formatted_name = get_formatted_name(f_name,l_name)
    print(('\nHello %s!') % formatted_name)
    a = input("\nIf you want to exit,Please input 'quit',or press 'enter' to continue.")
    if a == 'quit':
        key = False

# 编写一个while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函
# 数make_album() ,并将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。
def make_album(name,music):
    disk = {'name':name,'music':music}
    return disk
a = True
while True:
    name = input('\nPlease input singer name:')
    music = input('Please input music name:')
    disk = make_album(name.title(),music.title())
    print(disk)
    key = input("\nIf you want to exit,Please enter 'quit'")
    if key == 'quit':
        break

#接上一题将每次用户输入的信息变成字典并保存到列表中。
def make_album(name,music):
    disk = {'name':name,'music':music}
    return disk
a = True
disks = []
while True:
    name = input('\nPlease input singer name:')
    music = input('Please input music name:')
    disk = make_album(name.title(),music.title())
    disks.append(disk)
    key = input("\nIf you want to exit,Please enter 'quit'")
    if key == 'quit':
        break
print(disks)

#传递列表
def greet_users(names):
    for name in names:
        print('Hello %s!'% name.title())
usernames = ['jacky','alex','bob']
greet_users(usernames)


# 在函数中修改列表
# 我们可编写两个函数,每个都做一件具体的工作,只是效率更高。第一个函数将负责处理打印设计的工作,而第二个将概述打
# 印了哪些设计:
def print_models(unprinted_desings,completed_models):
    while unprinted_desings:
        current_design = unprinted_desings.pop()
        print('Printing model: %s' % 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)

unprited_designs = ['iphone case','robot pendant','dodecachedron']
comleted_models = []
print_models(unprited_designs[:],comleted_models)       #使用[:]向函数传递列表的副本,不会影响原列表。
show_completed_models(comleted_models)
print(unprited_designs)



# 创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians() 的函数,编写一个名为make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the
# Great”。在调用函数make_great() 时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的
# 列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians() ,确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字
# 样“the Great”的魔术师名字。
def show_magicians(new_magicians):
    for name in new_magicians:
        print(name.title())

def make_great(magicians,new_magicians):
    while magicians:
        magician = magicians.pop()
        magician = 'The Great %s.' % magician
        new_magicians.append(magician)

magicians = ['jacky','alex','bob']
new_magicians = []

make_great(magicians[:],new_magicians)

show_magicians(new_magicians)
show_magicians(magicians)


# 传递任意数量的实参
def make_pizza(*toppings):  #星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。
    print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

#遍历实参并打印
def make_pizza(*toppings):
    print('\nMaking a pizza with the floowing toppings:')
    for topping in toppings:
        print('-%s' % topping.title())
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')


# 结合使用位置实参和任意数量实参
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','jacky',
    location = 'china',
    filed = 'physics',ciry = 'shanghai')
print(user_profile)

# 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客
# 点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。

def sandwich(*shicai):
    print('\n你的配料有:')
    for i in shicai:
        print('-%s'% i)
sandwich('水','油','面粉','鸡蛋','沙拉')


# 编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可
# 少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:car = make_car('subaru', 'outback', color='blue', tow_package=True)

def make_car(brand,model,**cars_info):
    details = {}
    details['品牌'] = brand
    details['型号'] = model
    for key,value in cars_info.items():
        details[key] = value
    return details

car = make_car('subaru', 'outback', 颜色='blue', tow_package=True)
print(car)


# 将函数存储在模块中

# 导入整个模块
def make_pizza(size,*toppings):
    print('\nMaking a %s-inch pizza with the following toppings:')
    for topping in toppings:
        print('-topping')
#在同目录下建立一个making_pizza.py并写入以下内容:
import pizza    #导入上面写的模块
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')



#导入特定的函数
from moudle_name import function_name
#通过逗号分隔,导入任意数量的函数
from module_name import function_0, function_1, function_2


#使用as给函数指定别名
from moudle_name import function_name as fn

#使用as给模块指定别名
import moudle_name as fn

#导入模块中的所有函数
from moudel_name import *


函数编写指南
编写函数时,需要牢记几个细节。应给函数指定描述性名称,且只在其中使用小写字母和下划线。描述性名称可帮助你和别人明白代码想要做什么。给模块命名时也应遵循上述
约定。
每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字符串格式。文档良好的函数让其他程序员只需阅读文档字符串中的描述就能够使用
它:他们完全可以相信代码如描述的那样运行;只要知道函数的名称、需要的实参以及返回值的类型,就能在自己的程序中使用它。

给形参指定默认值时,等号两边不要有空格:def function_name(parameter_0, parameter_1='default value')
对于函数调用中的关键字实参,也应遵循这种约定:function_name(value_0, parameter_1='value')

建议代码行的长度不要超过79字符,这样只要编辑器窗口适中,就能看到整行代码。如果形参很多,导致函数定义的长度超过了
79字符,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。

  

转载于:https://www.cnblogs.com/jacky-zhao/p/8028061.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值