函数返回值

  • 函数并非总是直接显示输出,它可以处理一些数据,并返回一个或一组值,函数返回的值被称为返回值。
  • 使用return语句将值返回到调用函数的代码行中
# 返回简单值
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
# 让实参变为可选
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

返回字典

  • 函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构
# 返回字典
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'}
# 混合案例:
def get_formatted_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("Please tell me your name: ")
f_name = input("First_name: ")
l_name = input("Last_name: ")
judge = input("Whether to continue running (y/n): ")
if (judge == 'n'):
break
else:
continue
formatted_name = get_formatted_name(f_name,l_name)
print("\nHello, " + formatted_name + "!")
Please tell me your name:
First_name: li
Last_name: yege
Whether to continue running (y/n): y
Please tell me your name:
First_name: wang
Last_name: erxiao
Whether to continue running (y/n): n

传递列表

  • 列表可能是名字、数字、或更复杂的对象如字典,将列表传递给函数后,函数就能直接访问其内容,使用列表来处理列表的效率
def greet_users(names):
'''向列表中的每位用户都发出简单的问候'''
for name in names:
msg = "Hello , " + name.title() + "!"
print(msg) usernames = ['hahaha','try','margot']
greet_users(usernames)
Hello , Hahaha!
Hello , Try!
Hello , Margot!

函数中修改列表

  • 将列表传递给函数后,函数就可以对其进行修改
  • 函数中对列表所作的任何修改都是永久性的,可以高效地处理大量数据
# 不使用函数传递
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表 completed_models 中
while unprinted_designs:
# 模拟根据设计制作 3D 打印模型的过程
current_design = unprinted_designs.pop()
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)
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:
# 模拟根据设计制作 3D 打印模型的过程
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(unprinted_designs)
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:
# 模拟根据设计制作 3D 打印模型的过程
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(unprinted_designs)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case The following models have been printed:
dodecahedron
robot pendant
iphone case
['iphone case', 'robot pendant', 'dodecahedron']

练习

# 1.魔术师
# 创建一个包含魔术师名字的列表,并将其传递给一个名为 show_magicians() 的函数,这个函数打印列表中每个魔术师的名字
names = ['liuqian','xiaowang','zhangsan','lisi']
def show_magicians(names):
for name in names:
print("The magicians names is " + name.title() + ".")
show_magicians(names)
The magicians names is Liuqian.
The magicians names is Xiaowang.
The magicians names is Zhangsan.
The magicians names is Lisi.
# 2.了不起的魔术师
# 在你为完成练习编写的程序中,编写一个名为 make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样 “the
# Great” 。调用函数 show_magicians() ,确认魔术师列表确实变了
names = ['liuqian','xiaowang','zhangsan','lisi']
def show_magicians(names):
for name in names:
print("The magicians names is " + name.title() + ".")
def make_great(names):
great_magicians = []
while names:
new_names = names.pop()
great_magician = new_names + "the Great"
great_magicians.append(great_magician)
for great_magician in great_magicians:
names.append(great_magician) show_magicians(names)
print("\n")
make_great(names)
show_magicians(names)
The magicians names is Liuqian.
The magicians names is Xiaowang.
The magicians names is Zhangsan.
The magicians names is Lisi. The magicians names is Lisithe Great.
The magicians names is Zhangsanthe Great.
The magicians names is Xiaowangthe Great.
The magicians names is Liuqianthe Great.
# 3.不变的魔术师
# 在调用函数 make_great() 时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的
# 列表,并将其存储到另一个列表中。分别使用这两个列表来调用 show_magicians() ,确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字
# 样 “the Great” 的魔术师名字。
def show_magicians(names):
for name in names:
print("The magicians names is " + name.title() + ".")
def make_great(names):
great_magicians = []
while names:
new_names = names.pop()
great_magician = new_names + "the Great"
great_magicians.append(great_magician)
print(names)
for great_magician in great_magicians:
names.append(great_magician)
print(names) names = ['liuqian','xiaowang','zhangsan','lisi']
show_magicians(names)
print("\n")
copy = names[:]
make_great(copy)
show_magicians((copy))
The magicians names is Liuqian.
The magicians names is Xiaowang.
The magicians names is Zhangsan.
The magicians names is Lisi. ['liuqian', 'xiaowang', 'zhangsan']
['liuqian', 'xiaowang']
['liuqian']
[]
['lisithe Great']
['lisithe Great', 'zhangsanthe Great']
['lisithe Great', 'zhangsanthe Great', 'xiaowangthe Great']
['lisithe Great', 'zhangsanthe Great', 'xiaowangthe Great', 'liuqianthe Great']
The magicians names is Lisithe Great.
The magicians names is Zhangsanthe Great.
The magicians names is Xiaowangthe Great.
The magicians names is Liuqianthe Great.

Python 函数返回值及传递列表的更多相关文章

  1. python函数2(返回值、传递列表...)

    python函数2(返回值.传递列表...) 1.返回值 1.1.返回简单的值 #返回简单值 def get_formatted_name(first_name,last_name): "& ...

  2. python函数返回值

    2016-08-09  15:01:38 python函数返回值使用return语句,可以返回任意类型的数.如果return语句执行,它之后的所有语句都不再执行. def func(x,y): pri ...

  3. Python 函数返回值、作用域

    函数返回值 多条return语句: def guess(x): if x > 3: return "> 3" else: return "<= 3&qu ...

  4. Python 函数返回值

    本章详细介绍 返回值: 0x 00 返回值简介 0x 01 指定返回值与隐含返回值 0x 02 return 语句位置与多条 return 语句 0x 03 返回值类型 0x 04 函数嵌套 0x 0 ...

  5. day09 python函数 返回值 参数

    day09 python   一.函数     1.函数         函数是对功能的封装         语法:         定义函数:             def 函数名(形参):    ...

  6. python 函数返回值笔记

    今天学习python时候学习到闭包和柯里化 感觉看概念时候不好理解,自己写下大概就明白点了 柯里化如下 定义一个加法函数 def add(x, y): return x + y 这是没有柯里化之前的函 ...

  7. python 函数返回值(总结)

    关键字:return 没有返回值的叫过程 def test1(): msg="我是一个过程" print(msg) 有return的叫函数 def test02(): msg=&q ...

  8. Python 函数返回值类型

    [ i for i in dir(set) if not i.startswith('_') ]   

  9. Python学习教程(learning Python)--2.3.4Python函数返回值

    本节讨论Python函数返回值问题. Python和C语言一样,也可以在函数结束时返回一个值.但在定义自己的Python函数时,是不需要指定返回值数据类型的,这和Python不关心变量的数据类型是一致 ...

  10. Python return语句 函数返回值

    return语句是从python 函数返回一个值,在讲到定义函数的时候有讲过,每个函数都要有一个返回值.Python中的return语句有什么作用,今天就来仔细的讲解一下. python 函数返回值 ...

随机推荐

  1. SpringCloud之旅

    现在大部分公司的项目架构都选择了微服务,我们公司也不例外,那么什么是微服务呢?今天就来开启SpringCloud之旅! SpringCloud是基于SpringBoot的一整套的微服务架构.他提供了微 ...

  2. springboot修改事务隔离级别

    [SpringBoot]事务的隔离级别.Spring的事务传播机制_51CTO博客_springboot事务隔离级别

  3. Qt使用API实现鼠标点击操作

    前段时间,工作需要进行数据录入,每次都要点击3次按钮,想让鼠标自行点击,只要下位机接入,就自动点击按钮把数据读出,录入到服务端,并且进行检测,说干就干,没有经验,那只有面向百度编程. 根据查到的资料, ...

  4. VS Code中使用live Server

    live server可以实时查看代码更改后的变化.测试十分快速. 1.安装live server 在扩展中搜索 live server,然后点击安装.等待安装完毕进行下一步配置. 2.打开设置界面: ...

  5. LVS负载均衡 2022年4月

    1. 负载均衡技术简介 2 1.1 负载均衡类型3 1.2 LVS简介4 1.3 Keepalived简介5 2. 负载均衡搭建主要步骤 6 2.1 LVS+Keepalived的负载均衡系统搭建6 ...

  6. Go_day08

    Go的Io流 获取文件信息 //获取文件 fileinfo, err := os.Stat("./aa.txt")//相对绝对路径都可以 if err != nil { fmt.P ...

  7. MFC 与 C++ 类型转换

    C++ 中到的类型转换很多,先记录下来,多了写成一个类 1.CString转int 1 CString cNum="9527"; 2 int iNum = 0; 3 iNum=at ...

  8. Echarts中slider滑块调整样式

    今天遇到了一个问题,记录一下. 效果图. 原型图 一个页面中,引入了echarts的柱状图来动态显示数据,由于柱状图太高,echarts没有自动生成的滚动条,所以就用slider滑块手写了一个,但是效 ...

  9. Jan Ozer:高清直播互动场景下的硬编码如何选型?

    前言 高清直播逐渐普及,硬编码也成为大势所趋.在 RTE 2022 大会上,来自 NETINT 的 Jan Ozer 通过一系列的对比测试结果,详细分享了如何为高清直播互动场景进行硬编码的技术选型. ...

  10. C++类的构造函数、析构函数、拷贝构造函数、赋值函数和移动构造函数详细总结

    目录 1. 五种函数介绍 2. 左值&右值怎么区分?怎么看? 3. 匿名对象的3种使用情况 4. 代码详细验证每个函数调用情况 4.1 测试 f_1 函数(函数形参测试 -- 值传递) 4.2 ...