函数的学习2——返回值&传递列表——参考Python编程从入门到实践
返回值
函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数的返回值被称为返回值。
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。
函数的学习2——返回值&传递列表——参考Python编程从入门到实践的更多相关文章
- 函数的学习1——定义函数&传递实参——参考Python编程从入门到实践
定义函数 def greet_user(): print("Hello") greet_user() # PEP8 函数和类的定义后空两行 1. 向函数传递参数 def greet ...
- Python中创建数值列表——参考Python编程从入门到实践
1. 函数range( )的使用 range( )函数可以生成一系列的数字: for value in range(1, 5): print(value) Note:运行结果是打印数字1到4,即该函数 ...
- 字典的学习1——参考Python编程从入门到实践
字典:从汉语词意的角度理解,字典就是一个工具书,可以查找某个字.词.成语等的详细解释,字与解释相对应,而Python中字典则是一些列键和值相对应. Python中,字典放在花括号{键:值}中,eg: ...
- 函数的学习3——传递任意数量的实参&将函数存储在模块——参考Python编程从入门到实践
传递任意数量的实参 形参前加一个 * ,Python会创建一个已形参为名的空元组,将所有收到的值都放到这个元组中: def make_pizza(*toppings): print("\nM ...
- 二、继续学习(主要参考Python编程从入门到实践)
操作列表 具体内容如下: # 操作列表 # 使用for循环遍历整个列表. # 使用for循环处理数据是一种对数据集执行整体操作的不错的方式. magicians = ['alice', 'david' ...
- 字典的学习2——参考Python编程从入门到实践
遍历字典 1. 遍历所有键值对 eg1: user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi',}for key, v ...
- 使用while循环来处理列表和字典——参考Python编程从入门到实践
1. 在列表之间移动元素 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,知道没有未验证 ...
- Python中使用列表的一部分——参考Python编程从入门到实践
处理列表中的部分元素——切片 1. 切片 players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0: ...
- Python编程从入门到实践笔记——函数
Python编程从入门到实践笔记——函数 #coding=gbk #Python编程从入门到实践笔记——函数 #8.1定义函数 def 函数名(形参): # [缩进]注释+函数体 #1.向函数传递信息 ...
随机推荐
- LeetCode 801. Minimum Swaps To Make Sequences Increasing
原题链接在这里:https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/ 题目: We have two in ...
- SpringCloud过滤filter
目录 配置文件 application.yml eureka: client: service-url: defaultZone: http://localhost:8001/eureka serve ...
- Tomcat配置二级域名的分配与访问
回顾tomcat Tomcat是Apache软件基金会(Apache Software Foundation)的一个顶级项目,由Apache, Sun和其他一些公司及个人共同开发,是目前比较流行的We ...
- 这里是DDOSvoid的blog
由于博主已经退役,博客现由 @一扶苏一 代为维护. DDOSvoid 在生前退役前写下了大量的 blog 存在本地,现在由他的弟子 一扶苏一 整理编纂成为题单慢慢上传,是为<论语>< ...
- python3 报错UnicodeEncodeError
在ubuntu执行python3的时候,出现 UnicodeEncodeError: 'latin-1' codec can't encode characters in position 10-18 ...
- $(window).load()方法的使用场景
一.$(window).load().window.onload=function(){}和$(document).ready()方法的区别 1.$(window).load() 和window.on ...
- Wordpress 获取 custom post type 的当前文章 分类信息
// knowledgebase_category 为 custom post type taxonomy $terms = get_the_terms( get_the_ID() , 'knowle ...
- word/wps 制作下拉列表
准备: 1.数据页 2.项目名称sheet 3.问题类型sheet 开始制作: 数据 --- 有效性 --- 允许“序列” --- 来源 -- 其他sheet页“单元格”选择范围 回车.确定 即可
- js object 添加键值
第一种方法let obj ={"name":"tom","age":16}let key = "id";let valu ...
- k8s记录-kube-dns(core-dns)配置(七)
docker search corednsdocker pull xxx 拉取镜像(根据实际情况选择)docker tag xxx coredns/coredns:latestdocker tag c ...