搜索
首页后端开发Python教程Python 教程 - 函数

Python 教程 - 函数

Jan 06, 2025 pm 01:52 PM

介绍

函数是一个包含指令的可调用单元,旨在减少代码重复并组织复杂的任务。有两种类型:void 函数(无返回值)和有返回值的函数。

这是Python中函数的基本结构。

def function_name(args):
    function body

这是 Python 中 void 函数(无返回值)的示例。

# create a function
def hello():
    print("hello!")

# call the function
hello()

输出

hello!

基于上面的代码,创建了名为 hello() 的函数。通过指定函数名称后跟括号 () 来调用该函数。

这是一个带有返回值的函数示例。

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

输出

6

基于上面的代码,创建了名为 add() 的函数来对两个数字求和。 add() 函数的返回值存储在 result 变量中。

使用返回值函数时,请确保使用返回值。

参数和关键字参数

Python 中的函数可以动态地接受多个参数。有两种方法可以在函数中实现多个参数:

  • 参数:多个参数在函数中实现,无需指定关键字。参数可以使用 *args.

  • 来实现
  • 关键字参数:多个参数在具有指定关键字的函数中实现。关键字参数可以使用 **kwargs 来实现。

参数和关键字参数都必须位于函数中参数定义的最后位置。

这是使用参数方法动态计算数字总和的多个参数实现的示例。

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))

输出

3
6
24

基于上面的代码,可以使用不同数量的参数来调用 sum() 函数。

这是使用关键字参数方法实现多个参数的示例。

def display_info(name,**kwargs):
    print("========")
    print(f"name: {name}")
    print("other informations")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("========")

display_info("john",job="programmer",company="acme inc")
display_info("doe",job="programmer",company="acme inc",skills="go,java,php")

输出

========
name: john
other informations
job: programmer
company: acme inc
========
========
name: doe
other informations
job: programmer
company: acme inc
skills: go,java,php
========

基于上面的代码,可以使用不同数量的参数来调用display_info()函数。通过使用**kwargs,可以用关键字定义参数。

参数和关键字参数可以一起使用。这是一个例子。

def display(*args,**kwargs):
    print("===========")
    print("items")
    for arg in args:
        print(arg)
    print("other information")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("===========")

display("apple","coffee","milk",payment="cash")
display("TV","Camera",payment="cash",delivery="express")

输出

===========
items
apple
coffee
milk
other information
payment: cash
===========
===========
items
TV
Camera
other information
payment: cash
delivery: express
===========

递归函数

递归函数是在完成任务时调用自身的函数。递归函数可以解决很多问题,包括阶乘数、斐波那契数列等等。

递归函数有两个主要组成部分:

  • 基本情况:基本情况定义函数何时停止。
  • 递归关系:递归关系定义了函数的递归过程。

在此示例中,阶乘计算是使用递归函数实现的。

def function_name(args):
    function body

输出

# create a function
def hello():
    print("hello!")

# call the function
hello()

让我们仔细看看阶乘()函数。该函数涉及两个组件:

  • 基本情况:如果 n 的值等于 0 或 1,则函数执行终止。

  • 递归关系:当n大于1时函数执行。

hello!

factorial() 函数如下图所示。

Python Tutorial - unction

拉姆达

lambda 是一个匿名函数。 lambda 可以包含许多参数,就像一般的函数一样。 lambda 函数适合创建直接返回值的小函数。

这是 sum() 函数的示例。

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

这是 lambda 函数对两个数字求和的示例。 lambda 函数存储在名为 sum_func 的变量中。

6

要使用 lambda 函数,请通过变量名称调用该函数。

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))

地图和过滤器

地图功能

map() 函数为列表中的每个项目执行提供的回调函数。

这是 map() 函数将每个数字乘以 3 的示例。

3
6
24

输出

def display_info(name,**kwargs):
    print("========")
    print(f"name: {name}")
    print("other informations")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("========")

display_info("john",job="programmer",company="acme inc")
display_info("doe",job="programmer",company="acme inc",skills="go,java,php")

基于上面的代码,triple()函数充当map()函数的回调,这意味着为数字列表中的每个项目调用triple()函数。然后,map() 函数的结果被转换为列表,然后存储在名为 result 的变量中。

上面的示例可以使用 lambda 函数进行简化。

========
name: john
other informations
job: programmer
company: acme inc
========
========
name: doe
other informations
job: programmer
company: acme inc
skills: go,java,php
========

输出

def display(*args,**kwargs):
    print("===========")
    print("items")
    for arg in args:
        print(arg)
    print("other information")
    for k, val in kwargs.items():
        print(f"{k}: {val}")
    print("===========")

display("apple","coffee","milk",payment="cash")
display("TV","Camera",payment="cash",delivery="express")

过滤功能

filter() 函数根据给定的回调函数选择列表中的项目。 filter() 函数适合使用提供的回调函数过滤列表中的项目。 filter() 函数需要一个返回布尔值的回调函数。

这是 filter() 函数仅选择列表中偶数的示例。

===========
items
apple
coffee
milk
other information
payment: cash
===========
===========
items
TV
Camera
other information
payment: cash
delivery: express
===========

输出

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

# call the function
result = factorial(5)

print(result)

基于上面的代码,filter()函数使用is_even()作为回调函数从列表中选择偶数。

可以使用 lambda 函数简化此示例。

120

输出

def function_name(args):
    function body

示例 - 删除重复代码

该功能可用于删除重复代码。例如,有两个函数,称为register()和login()。这两个函数都使用验证过程。

# create a function
def hello():
    print("hello!")

# call the function
hello()

验证过程有重复的代码。要删除这些重复项,可以将验证过程包装在单独的函数中。

hello!

validate()函数可以在register()和login()函数内部使用。

# create a function with return value
def add(a,b):
    return a + b

result = add(2,4)

print(result)

基于上面的代码,代码更干净,更容易修改,因为如果更新额外的验证规则,可以在一处(validate()函数内部)更新验证规则。

尖端

这些是在 Python 中使用函数时的关键技巧。

  • 该函数必须完成单个任务。如果需要多个任务,请为其他任务创建一个单独的函数。

  • 函数参数的最大数量为 3。如果参数看起来超过 3,请考虑为函数参数使用专用数据对象。

函数参数的最大数量似乎有争议。

这是使用参数的 create_account() 函数的示例。

6

可以修改 create_account() 函数以使用数据对象来获得更简洁的代码。

def sum(*args):
    result = 0
    for arg in args:
        result += arg
    return result

print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,4,3,2))
  • 使用文档来解释功能描述。可以使用“””语法添加文档。

这是在函数内使用文档的示例。

3
6
24

来源

  • 函数中的参数和关键字参数
  • 递归函数图解

希望这篇文章对你学习Python有所帮助。如果您有任何意见,请在评论区告诉我。

以上是Python 教程 - 函数的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?列表和阵列之间的选择如何影响涉及大型数据集的Python应用程序的整体性能?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

说明如何将内存分配给Python中的列表与数组。说明如何将内存分配给Python中的列表与数组。May 03, 2025 am 12:10 AM

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

您如何在Python数组中指定元素的数据类型?您如何在Python数组中指定元素的数据类型?May 03, 2025 am 12:06 AM

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

什么是Numpy,为什么对于Python中的数值计算很重要?什么是Numpy,为什么对于Python中的数值计算很重要?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

讨论'连续内存分配”的概念及其对数组的重要性。讨论'连续内存分配”的概念及其对数组的重要性。May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

您如何切成python列表?您如何切成python列表?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

在Numpy阵列上可以执行哪些常见操作?在Numpy阵列上可以执行哪些常见操作?May 02, 2025 am 12:09 AM

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,减法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Python的数据分析中如何使用阵列?Python的数据分析中如何使用阵列?May 02, 2025 am 12:09 AM

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具