Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced content levelIntermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
119
9
函数
职能越小,管理越好。
——
C. Northcote Parkinson
到目前为止,本书所有的
Python
码示例都是一些小的片段。对于小任务而言,固然不
错,但没人想一直重复输入这些代码片段。我们需要用某种方法将较长的代码组织成可管
理的部分。
代码重用的第一步是使用函数。
函数
是独立于其他代码的具名的代码段。它可以接受任意
数量和类型的输入
参数
,返回任意数量和类型的输出
结果
和函数相关的事有两件:
定义
函数,接受
0
个或多个参数;
调用
函数,获得
0
个或多个结果。
9.1
使用
def
定义函数
要定义
Python
函数,可以依次输入
def
、函数名称、带有函数输入参数的圆括号,最后
以冒号(
:
)作结。函数名称的规则和变量名一样(必须以字母或
_
起始,只能包含字母、
数字或
_
)。
下面一步一步来,先定义并调用一个没有参数的函数。最简单的
Python
函数如下:
>>> def do_nothing():
... pass
即便像这种没有参数的函数,圆括号和冒号也不能少。下一行需要缩进,就像缩进
if
句下的代码一样。
Python
要求使
pass
语句表明该函数不作任何操作。这就相当于书中
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.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223