【Python】函数的定义和函数的处理

是日要点

  • 函数定义
  • 函数定义的描述和处理。

函数定义

定义函数允许您定义一次并重复使用它,只要您想重复使用同一过程即可。
Def用于定义一个函数。 函数名旁边写的 (thing, basket) 是参数。

至于参数,我们将在以后的文章中详细讨论,但它们将是传递给函数的变量。 通过改变这个参数的值,即便使用相同的逻辑,结果也会改变。

python 复制代码
basket = ['apple', 'orange', 'banana', 'lemon']

def LookIntoTheBasket(thing, basket):
    for fruit in basket:
        if fruit == thing:
            print(thing,'is in the basket.')
            break
    else:
        print(thing,'is not in the basket.')

LookIntoTheBasket('apple', basket)
LookIntoTheBasket('mikan', basket)
python 复制代码
apple in the basket.
mikan is not in the basket.

功能分配

可以将一个函数分配给另一个变量。 通过一个示例来看看它是如何工作的。

python 复制代码
value = LookIntoTheBasket

value('kaki', basket)
python 复制代码
kaki is not in the basket.

函数返回值

如果没有明确指定

返回值是函数执行某些处理并返回结果的值。

首先,前面的函数没有指定返回值。 print函数是一个过程,而不是一个返回值。

在这种情况下,返回值将为 None,所以让我们检查一下。

请注意,结果第一行中的apple is in the basket并不是返回值,而是打印函数处理的结果。

python 复制代码
print(value('apple', basket))
python 复制代码
apple is in the basket.
None

当明确指定时

现在指定返回值。 指定return来指定返回值。

例如,稍微改变一下前面的示例,使用 return 而不是 print 来接收结果作为返回值,如下所示。

python 复制代码
basket = ['apple', 'orange', 'banana', 'lemon']

def LookIntoTheBasket(thing, basket):
    for fruit in basket:
        if fruit == thing:
            return thing + ' is in the basket.'
    else:
        return thing + ' is not in the basket.'

print(LookIntoTheBasket('apple', basket))
python 复制代码
apple is in the basket.

通过这种方式显式指定返回值,将不再像以前那样返回 None 。

相关推荐
用户83562907805117 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805117 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生1 天前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师1 天前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf1 天前
FastAPI 如何连接 MySQL
后端·python
apocelipes2 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780512 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python