欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-01 12:45:09
返回值 函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数的返回值被称为返回值。 1. 简单的返回值 调用返回值的函数时,需要提供一个变量存储返回的值。 2. 让实参变成可选的 然而并非每个人都有中间名,怎样让中间名变成可选呢? 给形参中间名一个空字符为默认值,将其移动至形 ......

返回值

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

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。

上一篇: Linux磁盘管理

下一篇: 选课系统