Python基础学习_函数数def_返回值及返回值类型_函数块

一、 返回值

函数作用:显示输出、处理数据并返回数据结果

函数返回值的定义:函数返回值被称为返回值

写法: 函数体内 return 返回值 (将值返回到调用函数的代码行)

返回值类型:

“”"
1、返回简单值
2、返回字典
3、列表
4、复杂数据结构
“”"

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)

结果:

Jimi Hendrix

1.1 将实参变成可选的

可选值作用:让函数能够处理各种不同情形,确保函数调用尽可能简单

原始例子

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('jojn', 'lee', 'hooker')
print(musician)

结果:

Jojn Lee Hooker

将实参变为可选案例 将可选实参变为空字符串,并在循环体中加入if_else语句

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(musician)

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

结果:

Jimi Hendrix
John Lee Hooker

注意:使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。

这让python依然能够正确的解读位置实参

这个例子说明,当一个实参的是可选时(即有默认值以及可选值),

这个实参必须放到最后一个实参位置

1.2、返回字典

def build_person(first_name,last_name):
    """返回一个字典,其中包含有关一个人的信息"""
    person = {'first':first_name, 'last':last_name}
    return person

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

结果:

{'first': 'jimi', 'last': 'hendrix'}
1.2.1扩展 增加姓名、职业
def build_person(first_name, last_name, age = '', occupation = ""):
    """返回一个字典,其中包含有关一个人的信息"""
    person = {
        'first':first_name,
        'last':last_name,
        }
    if age:
        person['age']  = age
    if occupation:
        person['occupation'] = occupation
    return person

结果:

{'first': 'jimi', 'last': 'hendrix', 'age': 36, 'occupation': 'teacher'
1.2.3 结合使用函数和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.title() + "!")

结果

Please tell me your name: 

First name: zhang

Last name:  

Hello,Zhang !

Please tell me your name: 

First name: guan

Last name:  yu

Hello,Guan Yu!

Please tell me your name: 
注意:由于是无限循环,所以按快捷键ctrl + c 结束循环
1.2.4修改设置退出条件
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.title() + "!")

结果:

Please tell me your name: 
(Enter 'q' at any time to quit)

First name: zhang

Last name:  fei

Hello,Zhang Fei!

Please tell me your name: 
(Enter 'q' at any time to quit)

First name: guan

Last name:  yu

Hello,Guan Yu!

Please tell me your name: 
(Enter 'q' at any time to quit)

First name: q

1.4 传递列表

def greet_users(names):
    """向列表中的每一位用户都发出邀请的问候"""
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)


usernames  = ['hannah','ty','margot']
greet_users(usernames)

结果:

Hello, Hannah!
Hello, Ty!
Hello, Margot!
1.4.1 在函数中修改列表(修改列表是永久性的)

创建一个列表,其中包含一些要打印的设计

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

模拟打印每个设计,直到没有未打印的设计为止

打印每个设计后,都将其移到表completed_models中

while unprinted_designs:
    current_design = unprinted_designs.pop()
    
    # 模拟根据设计制造3A打印模型的过程
    print("Print model: " + current_design)
    completed_models.append(current_design)


# 显示打印好的所有模型
print("\nThe following models have been printed: ")
for completed_model in completed_models:
    print(completed_model)
    
print(unprinted_designs) # 结果为空,说明列表被永久性修改了


# 显示打印好的所有模型
print("\nThe following models have been printed: ")
for completed_model in completed_models:
    print(completed_model)
    
print(unprinted_designs) # 结果为空,说明列表被永久性修改了

结果:

Print model: dodecahedron
Print model: robot pendant
Print model: iphone case

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

封装成两个函数

1、打印模型函数

def print_models(unprinted_designs,completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其移到表completed_models中
    """
    
    while unprinted_designs:
        current_design = unprinted_designs.pop()
    
        # 模拟根据设计制造3A打印模型的过程
        print("Print model: " + current_design)
        completed_models.append(current_design)

2、显示函数

def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed: ")
    for completed_model in completed_models:
        print(completed_model)

3、主函数

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

print("\nunprinted_designs未处理前结果",":",unprinted_designs)
print_models(unprinted_designs, completed_models)

print("unprinted_designs处理后结果",":",unprinted_designs)
show_completed_models(completed_models)

结果:

unprinted_designs未处理前结果 : ['iphone case', 'robot pendant', 'dodecahedron']
Print model: dodecahedron
Print model: robot pendant
Print model: iphone case
unprinted_designs处理后结果 : []

The following models have been printed: 
dodecahedron
robot pendant
iphone case

上面两个函数给我们的启发:每个函数都应只负责一项具体的工作,

这样能便于项目的维护和扩展

总结:

1、返回值类型:返回简单值、返回字典、返回列表、返回复杂数据结构
2、实参变为可选注意事项:可变实参必须位于没有默认值的实参的后面,然后在函数体中使用if-else语句来对可变实参进行分情况写执行条件即可
3、函数块优点:其一使主程序变得可维护和可扩展;其二,使复制的事情简单化(即将复杂的事情拆分为许多小步骤来实现)

你可能感兴趣的:(笔记,python,学习,开发语言)