Python 3 《function》入门练习

一、定义函数

1、一个打印问候语的简单函数,名为greet_user():

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

greet_user()

二、传递参数

2、位置信息实参,函数调用时务必将位置放对

#-------位置实参------
def describe_pet(pet_type, pet_name: object):
    """显示宠物的信息"""
    print("\nI have a " + pet_type + ".")
    print("The name of my pet " + pet_type + "is " + pet_name.title() + ".")

describe_pet('hamster', "Harry")
describe_pet('dog', 'willie')  #可以调用函数任意次

3、关键字实参,避免了位置错乱出现的问题

#------------关键字实参-----------------
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')

4、为形参设定默认值,那么在调用函数时,不给形参赋值,便会使用默认值

    注意: 使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。这让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 = 'harry')
describe_pet('harry')

#---------------混合调用方式------------------
# 一条名为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')

三、返回值

5、让实参编程可以选择的,因为不一定每一次调用都需要对所有的形参赋值

#-----------------让实参编程可选的---------------------
def get_formatted_name(first_name, middle_name, last_name):
    """返回整洁的姓名"""
    full_name = first_name + ' ' + middle_name + ' ' + last_name
    return full_name.title()

musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)


#-----------------不是所有的人都有  middle name ----------------------
#--------处理方式如下所示-----------
def get_formatted_name(first_name, last_name, middle_name = ' ' ):
    """返回整洁的姓名"""
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name
        return full_name.title()
    else:
        full_name = first_name + ' ' + last_name
        return full_name.title()

musician = get_formatted_name('jimi','hendrix')
print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)

6、返回一个字典

#-----------------返回字典-------------------
def build_person(first_name, last_name, age=' '):
    """返回一个字典,包含的是关于一个人的信息"""
    person = {'first': first_name, 'last': last_name, 'age': age}  #字典中也可以不存年龄
    if age:
        person['age'] = age
    return person

mu = build_person('Christal', 'LI', age = 27)
print(mu)

7、结合前面所学知识的一个小应用

#*****************一个实际应用的实例****************
def get_formal_name(f_name, l_name):
    """Return  formal name"""
    full_name = f_name + ' ' + l_name
    return full_name.title()

#这是一个无限循环
while True:
    print('\nPlease tell me your name:')
    print("(enter 'q' at any time to quit)")

    fr_name = input('First_name')
    if fr_name == 'q':
        break

    ls_name = input('Last_name')
    if ls_name == 'q':
        break

    formal_name = get_formal_name(fr_name,ls_name)   #将输入的值作为实参
    print("\nHello, " + formal_name + '!')

四、传递列表

8、函数简单传递列表

#*************传递列表 *******************
def greet_user(names):
    """向列表中的每一个用户都发出简单的问候"""
    for name in names:
        msg = "Hello, " + name.title() + '!'
        print(msg)

usernames = ['christal', 'han','myh']
greet_user(usernames)

9、函数汇总修改列表,分别对比了应用函数和不应用函数两种情形,利用函数后主程序更加简洁,可移植性强,可修改性强

#------------没有利用函数的情形----------------
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
    current_design = unprinted_designs.pop()    #末尾弹出
    #模拟根据设计制作3D打印模型的过程
    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)

#------------利用函数的情形---------------
#------定义2个函数,一个是完成打印过程的,
                  # 一个是显示打印结果的
def print_process(unprinted_design, printed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_design:
        currenr_prin = unprinted_design.pop()

        # 模拟根据设计制作3D打印模型的过程
        print("The completed model is " + currenr_prin)
        printed_models.append(currenr_prin)

def show_completedmodel(completed_models):
    """显示所有打印好的模型"""
    print("\nThe all finished models are as following: ")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_process(unprinted_designs, completed_models)
show_completedmodel(completed_models)

10、如果要禁止修改列表,即保留未打印设计的列表,因此需要将未打印列表的副本传递给函数进行处理,进而保留原始的列表信息,要将列表的副本传递给函数,可以像下面这样做:function_name(list_name[:]),切片表示法[:]创建列表的副本

def print_process(unprinted_design, printed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到列表completed_models中
    """
    while unprinted_design:
        currenr_prin = unprinted_design.pop()

        # 模拟根据设计制作3D打印模型的过程
        print("The completed model is " + currenr_prin)
        printed_models.append(currenr_prin)

def show_completedmodel(completed_models):
    """显示所有打印好的模型"""
    print("\nThe all finished models are as following: ")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_process(unprinted_designs[:], completed_models)
show_completedmodel(completed_models)

11、传递任意参数的实参

形参可以表示为* name, 形参名*toppings中的星号让Python创建一个名为toppings的空元组,,并将收到的所有值都封装到这个元组中。函数体内的print语句通过生成输出来证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用,注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此:

#--------------传递任意实数的实参-----------------
def make_piza(*toppings):
    """打印顾客所点的配料"""
    print("\nMaking the pizza with the following toppings:")
    for topping in toppings:
        print(topping)

make_piza('pepperoni')
make_piza('mushroom','green peppers','extra chess')

12、结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。


def ma_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

ma_pizza(16, 'pepperoni')
ma_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

13、使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。

形参**user_info中的两个星号让Python创建一个名为user_info的空字典,

#---------使用任意数量的关键字实参-------------
#我们只知道要传递用户的信息,但是不知道要传递的是什么信息,传递多少信息
def  build_profile(first, last, **user_info):
    """创建一个字典,其中包括包括我们知道的关于用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.item():
        profile[key] = value
    return profile

user_profile = build_profile('albert','einstein',
                             location = 'princeton',
                             field = 'physics')
print(user_profile)

14、将函数存储在模块中

函数的优点之一是,使用它们可将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解得多。你还可以更进一步,将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。

(1)要让函数是可导入的,得先创建模块。模块是扩展名为.py的文件,包含要导入到程序中的
代码,导入整个模块

下面来创建一个包含函数make_pizza()的模块,保存为pizza.py

def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\nMaking a " + str(size) +
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)

接下来,我们在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza()两次:

#--------making_pizzas.py------------

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

(2)导入特定的函数,模块中的指定函数,使用如下的语句:

from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:

from module_name import function_0, function_1, function_2

用这中方法展示上述事例中的调用,代码段如下:

from pizza import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

(3)使用as给函数一个别名

如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可指定简短
而独一无二的别名——函数的另一个名称,类似于外号。

此时,函数的模块的调用代码如下:from module_name import function_name as fp

from pizza import make_pizza as mp

mp(16,'pepperoni)
mp(12,'mushroom','green peppers','extra cheese')

(4)使用as给模块别名,

使用方法为:import modle_name as mn,上述实例中可以改写为:

import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

(5)导入模块的所有函数

导入方法为:from module_name import *

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

编写函数小结:

       编写函数时,

1)给函数指定描述性名称,且只使用小写字母和下划线,

2)在函数的定义后面必须包含功能性注释,

3)给形参默认值时,等号两边不要有空格,

                def function_name(parameter_0, parameter_1='default value')

4)对于函数调用中的关键字实参,也遵循此约定

                function_name(value_0,  parameter_1='value')      

5) 建议代码行的长度不要超过79字符,如果形参很多,可在函数定义中输入左括号后按回车键,并在下一行按两次Tab键,从而将形参列表和只缩进一层的函数体区分开来。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清韵逐梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值