Skip to Content
Python入门指南, 3rd Edition
book

Python入门指南, 3rd Edition

by Bill Lubanovic
September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
O'Reilly Media, Inc.
Content preview from Python入门指南, 3rd Edition

第 10 章 函数 函数

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

函数越小,管理越大。

C.诺斯科特-帕金森

所以到目前为止,我们所有的 Python 代码示例都是一些小片段。 这些片段对于小任务来说是很好的,但没有人愿意一直重复输入片段。 我们需要一种方法,将较大的代码组织成易于管理的片段,并使其可重用。

代码重用的第一步就是函数:一段独立于所有其他代码的命名代码。 函数可以接受任意数量和类型的输入参数,并返回一个结果。结果可以如下所示:

Python 返回值None

单个对象,可能只有一个值,也可能有多个元素(如元组或 list)。

一个函数可以执行两个操作:

  • 使用零个或多个参数定义

  • 使用零个或多个参数调用它,并得到结果

用 def 定义函数

要定义一个 Python 函数,您需要键入def 、函数名、括住函数输入参数的括号,最后是冒号 (:)。函数名的规则与变量名相同 (必须以字母或_ 开头,并且只包含字母、数字或_)。

让我们一步一步地进行定义,首先定义并调用一个没有参数的函数。 下面是最简单的 Python 函数:

>>> def do_nothing():
...     pass

为什么 ,pass ? Python 不允许在这里出现空行,所以需要pass 来说 "嘿,这里没什么可看的"。

即使是像这样一个没有参数的函数,在它的定义中仍然需要括号和冒号。 下一行需要缩进,就像在if 语句下缩进代码一样。 Python 需要pass 语句来表示这个函数什么也不做。它相当于This page intentionally left blank(尽管它不再是了)。

用括号调用函数

只需键入该函数的名称和括号即可调用该函数。该函数如其所宣传的那样,什么也不做,但却做得非常好:

>>> do_nothing()
>>>

现在,让我们定义并调用另一个函数,它没有参数,只打印一个单词:

>>> def make_a_sound():
...     print('quack')
...
>>> make_a_sound()
quack

当您调用make_a_sound() 函数时,Python 会运行其定义中的代码。在这种情况下,它会打印一个单词,然后返回主程序。

让我们试试一个没有参数但返回值的函数:

>>> def agree():
...    return True
...

您可以使用if 调用该函数并测试其返回值:

>>> if agree():
...     print('Splendid!')
... else:
...     print('That was unexpected.')
...
Splendid!

您刚刚迈出了一大步。将函数与测试(如if)和循环(如while )相结合,可以让您更轻松地完成以前无法完成的任务。

参数

在 这一点上,是时候在括号里放点东西了。让我们定义带有一个名为anything 的参数的echo() 函数。它使用return 语句将anything 的值发送两次给它的调用者,中间有一个空格:

>>> def echo(anything):
...    return anything + ' ' + anything
...
>>>

现在,让我们用Rumplestiltskin 字符串调用echo()

>>> echo('Rumplestiltskin')
'Rumplestiltskin Rumplestiltskin' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

生成式人工智能设计模式

生成式人工智能设计模式

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9798341668898