返回值

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

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. 函数的学习1——定义函数&传递实参——参考Python编程从入门到实践

    定义函数 def greet_user(): print("Hello") greet_user() # PEP8 函数和类的定义后空两行 1. 向函数传递参数 def greet ...

  2. Python中创建数值列表——参考Python编程从入门到实践

    1. 函数range( )的使用 range( )函数可以生成一系列的数字: for value in range(1, 5): print(value) Note:运行结果是打印数字1到4,即该函数 ...

  3. 字典的学习1——参考Python编程从入门到实践

    字典:从汉语词意的角度理解,字典就是一个工具书,可以查找某个字.词.成语等的详细解释,字与解释相对应,而Python中字典则是一些列键和值相对应. Python中,字典放在花括号{键:值}中,eg: ...

  4. 函数的学习3——传递任意数量的实参&将函数存储在模块——参考Python编程从入门到实践

    传递任意数量的实参 形参前加一个 * ,Python会创建一个已形参为名的空元组,将所有收到的值都放到这个元组中: def make_pizza(*toppings): print("\nM ...

  5. 二、继续学习(主要参考Python编程从入门到实践)

    操作列表 具体内容如下: # 操作列表 # 使用for循环遍历整个列表. # 使用for循环处理数据是一种对数据集执行整体操作的不错的方式. magicians = ['alice', 'david' ...

  6. 字典的学习2——参考Python编程从入门到实践

    遍历字典 1. 遍历所有键值对 eg1: user_0 = { 'username': 'efermi', 'first': 'enrico', 'last': 'fermi',}for key, v ...

  7. 使用while循环来处理列表和字典——参考Python编程从入门到实践

    1. 在列表之间移动元素 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,知道没有未验证 ...

  8. Python中使用列表的一部分——参考Python编程从入门到实践

    处理列表中的部分元素——切片 1. 切片 players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0: ...

  9. Python编程从入门到实践笔记——函数

    Python编程从入门到实践笔记——函数 #coding=gbk #Python编程从入门到实践笔记——函数 #8.1定义函数 def 函数名(形参): # [缩进]注释+函数体 #1.向函数传递信息 ...

随机推荐

  1. learning java FileInputStream

    public class FileInputStreamTest { public static void main(String[] args) throws IOException { var f ...

  2. GoCN每日新闻(2019-10-09)

    GoCN每日新闻(2019-10-09) GoCN每日新闻(2019-10-09) 1. 我们如何将服务延迟减少了98% https://blog.gojekengineering.com/the-n ...

  3. gitbook+git+typora 的使用过程

    Typora 下载地址:https://typora.io/ gitbook 第一步:安装 npm install -g gitbook-cli 第二步:使用 对要操作的文件夹执行命令 gitbook ...

  4. Alibaba Nacos:搭建Nacos平台

    1.下载安装包 https://github.com/alibaba/nacos/releases 往下翻,找到压缩包下载. 2.解压 tar -xvf nacos-server-$version.t ...

  5. 【自学Spring Boot】什么是Spring Boot

    为啥要有Spring Boot? 以前大学刚开始学java web的时候,需要搭建起web框架,当时使用的是SSH(struts+spring+hibernate),那就开始搭建吧,初学者哪里知道整套 ...

  6. NGINX Cache Management (.imh nginx)

    In this article, we will explore the various NGINX cache configuration options, and tips on tweaking ...

  7. hive中function函数查询

    1. desc function [函数名] desc function xpath; 查询用法: 2. desc function extended [函数名] desc function exte ...

  8. linux,卸载文件系统的时候,报busy情况的解决记录

    背景描述: 前几天由于文件系统io异常的问题,要对文件系统的属性进行修改,修改该参数需要将磁盘umount,在umount的过程中遇到问题,在此记录下. 处理过程: 1.执行umount进行卸载磁盘, ...

  9. Python3基础 dict __len__ 统计键值对的数量

             Python : 3.7.3          OS : Ubuntu 18.04.2 LTS         IDE : pycharm-community-2019.1.3    ...

  10. (转载)PyTorch代码规范最佳实践和样式指南

    A PyTorch Tools, best practices & Styleguide 中文版:PyTorch代码规范最佳实践和样式指南 This is not an official st ...