
上QQ阅读APP看书,第一时间看更新
1.3.6 函数
函数的应用非常广泛,Python除了内置的标准函数外,还支持自定义函数。创建单个输出的函数既可以使用def关键字,也可以使用匿名函数(lambda)。例如,定义一个函数f(x)=x3+2x,并求f(3)的值,有以下两种方法。
方法1:

方法2:

创建多个输出的函数只能使用def关键字,如图1.54所示。

图 1.54
需要注意以下两点。
(1)函数返回多个值,是Python特有的性质,VS Code将其作为元组显示(10,24),常见的调用多值函数的方法如下:

(2)函数的第一行def f(x, y, z):和函数体内的代码行不能对齐,如果在第一行的冒号后按Enter键时,光标没有自动停在u前方的位置,这时按Tab键。