程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

函数的学习2——返回值&传递列表——参考Python编程从入门到实践

发布于2019-08-08 11:00     阅读(435)     评论(0)     点赞(4)     收藏(0)


返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数的返回值被称为返回值。

1. 简单的返回值

复制代码
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)
复制代码

调用返回值的函数时,需要提供一个变量存储返回的值。

2. 让实参变成可选的

复制代码
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)
复制代码

然而并非每个人都有中间名,怎样让中间名变成可选呢?

复制代码
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('john', 'hooker', 'lee')
print(musician)
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
复制代码

给形参中间名一个空字符为默认值,将其移动至形参列表的末尾;调用函数时确保实参中间名方最后。

3. 返回字典

复制代码
def build_person(first_name, last_name):
    person = {'first': first_name, 'last': last_name}
    return person


musician = build_person('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)
复制代码

4. 结合使用函数和while循环

复制代码
def get_formatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()


while True:
    print("\nPlease tell me your name:")
    f_name = input("First name: ")
    l_name = input("Last name: ")

    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")
复制代码

无限循环调用定义的函数,say hello everyone!!! 该在什么地方提供推出呢?

复制代码
def get_formatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()


while True:
    print("\nPlease tell me your name:")
    print("(enter 'q' at any time to quit)")
    f_name = input("First name: ")
    if f_name == 'q':
        break
    l_name = input("Last name: ")
    if l_name == 'q':
        break

    formatted_name = get_formatted_name(f_name, l_name)
    print("\nHello, " + formatted_name + "!")
复制代码

每次提示用户输入时均可推出。

传递列表

复制代码
def greet_users(names):
    for name in names:
        mag = "Hello, " + name.title() + "!"
        print(mag)


user_names = ['hannah', 'bob', 'margot']
greet_users(user_names)
复制代码

运行结果:

Hello, Hannah!
Hello, Bob!
Hello, Margot!

1. 在函数中修改列表

复制代码
# 创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

# 模拟打印每个设计,直到没有未打印的设计为止,打印后移至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:")
print(completed_models)
复制代码

运行结果:

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
['dodecahedron', 'robot pendant', 'iphone case']

 用函数如何表达上述代码的意思呢?

复制代码
def print_models(unprinted_designs, completed_models):
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        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函数调用之后,列表completed_models已经不是最初定义的空,所有列表unprinted_designs中的元素已转移至列表completed_models,接下来调用show_completed_models函数就将列表completed_models中的元素都打印出来。

2. 禁止函数修改列表

上述的例子中print_models函数调用之后,列表unprinted_designs中的元素均已移除,此时的列表为空。但若想保留列表中的元素呢?

print_models(unprinted_designs[:], completed_models)

 用切片法 [ : ] 创建列表副本,函数调用时使用的是列表的副本,而不是列表本身,此时函数中对列表做的修改不会影响到列表unprinted_designs。



所属网站分类: 技术文章 > 博客

作者:小姐姐抱抱我

链接:https://www.pythonheidong.com/blog/article/13445/9cb15175f097570ca5e8/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)