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

是日要点

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

函数定义

定义函数允许您定义一次并重复使用它,只要您想重复使用同一过程即可。
Def用于定义一个函数。 函数名旁边写的 (thing, basket) 是参数。
至于参数,我们将在以后的文章中详细讨论,但它们将是传递给函数的变量。 通过改变这个参数的值,即便使用相同的逻辑,结果也会改变。

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)
apple in the basket.
mikan is not in the basket.

功能分配

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

value = LookIntoTheBasket

value('kaki', basket)
kaki is not in the basket.

函数返回值

如果没有明确指定

返回值是函数执行某些处理并返回结果的值。
首先,前面的函数没有指定返回值。 print函数是一个过程,而不是一个返回值。
在这种情况下,返回值将为 None,所以让我们检查一下。
请注意,结果第一行中的apple is in the basket并不是返回值,而是打印函数处理的结果。

print(value('apple', basket))
apple is in the basket.
None

当明确指定时

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

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))
apple is in the basket.

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

相关推荐

  1. Python函数定义函数处理

    2023-12-13 21:44:03       61 阅读
  2. python函数定义调用

    2023-12-13 21:44:03       50 阅读
  3. Python定义调用函数

    2023-12-13 21:44:03       32 阅读
  4. python定义函数写循环批量处理数据集

    2023-12-13 21:44:03       62 阅读
  5. Python函数定义与使用

    2023-12-13 21:44:03       41 阅读
  6. 054、Python 函数概念以及定义

    2023-12-13 21:44:03       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-13 21:44:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-13 21:44:03       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-13 21:44:03       82 阅读
  4. Python语言-面向对象

    2023-12-13 21:44:03       91 阅读

热门阅读

  1. NoSQL

    2023-12-13 21:44:03       33 阅读
  2. 02.jsp复习

    2023-12-13 21:44:03       47 阅读
  3. 【Android开发-27】Android中位置服务GPS的用法详解

    2023-12-13 21:44:03       51 阅读
  4. 数据库工具:AI 拍档,最佳的矢量数据库

    2023-12-13 21:44:03       66 阅读
  5. 什么是CSharp?c#?

    2023-12-13 21:44:03       58 阅读
  6. Oracle 库恢复删除数据

    2023-12-13 21:44:03       53 阅读
  7. 神经网络以及深度学习案例分析

    2023-12-13 21:44:03       59 阅读
  8. leetcode 二数之和 三数之和 四数之和

    2023-12-13 21:44:03       55 阅读