【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 。

相关推荐
Cx330❀27 分钟前
【优选算法必刷100题】第038题(位运算):消失的两个数字
开发语言·c++·算法·leetcode·面试
Loo国昌29 分钟前
深入理解 FastAPI:Python高性能API框架的完整指南
开发语言·人工智能·后端·python·langchain·fastapi
chinesegf1 小时前
Ubuntu 安装 Python 虚拟环境:常见问题与解决指南
linux·python·ubuntu
醉舞经阁半卷书11 小时前
Python机器学习常用库快速精通
人工智能·python·深度学习·机器学习·数据挖掘·数据分析·scikit-learn
hoiii1871 小时前
16APSK/32APSK调制解调MATLAB仿真实现
开发语言·matlab·fpga开发
feifeigo1232 小时前
基于MATLAB的情感语音模板培训与识别实现方案
开发语言·matlab
JH30732 小时前
Java Spring中@AllArgsConstructor注解引发的依赖注入异常解决
java·开发语言·spring
码农水水2 小时前
米哈游Java面试被问:机器学习模型的在线服务和A/B测试
java·开发语言·数据库·spring boot·后端·机器学习·word
开源技术2 小时前
Violit: Streamlit杀手,无需全局刷新,构建AI面板
人工智能·python
C++ 老炮儿的技术栈2 小时前
C/C++ 中 inline(内联函数)和宏定义(#define)的区别
开发语言·c++·git·算法·机器人·visual studio