这是来自 kaggle 的 Python 课程,本文档试图翻译它的讲义 (tutorial) 内容,会对原内容进行增删,原课程带有相应的 exercise,如有网络条件推荐前往原课程学习。

课程链接:https://www.kaggle.com/learn/python

你可能在其他地方见过如print()和abs()这样的函数,它们的作用就像它们的名字一样,print()能够在屏幕上显示一些内容,而abs()能够给出一个变量的绝对值。在这节课中,你会学习怎样定义和使用函数。

获取帮助

或许你对前面提到的abs()函数不太了解,或者忘了它的作用。Python 自带的help()函数将会有很大帮助。可以说,学会使用help()函数,就掌握了理解其他所有函数的秘诀。
如下是一个例子:

  1. help(round)

输出内容Help on built-in function round in module builtins:

round(number, ndigits=None)
Round a number to a given precision in decimal digits.

  1. The return value is an integer if ndigits is omitted or None. Otherwise<br /> the return value has the same type as the number. ndigits may be negative.<br />(END)<br /> `help()`会在你的控制台上显示两个东西:
  1. 函数头:round(number, ndigits=None)。这一部分告诉我们round()函数需要一个可以称作number的参数。此外我们可以选择性地提供一个可以称作ndigits的参数。
  2. 函数功能简介

提示:当你在查找一个函数的帮助文档时,记得是把函数名称传进去,而不是调用这个函数之后的结果。

如果把调用round()函数之后的结果传进help()结果会怎样?看看下面的结果。

  1. help(round(-2.01))

输出结果Help on int object:

class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.int(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int(‘0b100’, base=0)
| 4
|
| Built-in subclasses:
| bool
|
| Methods defined here:
|
| abs(self, /)
| abs(self)
|
| add(self, value, /)
| Return self+value.
|
| and(self, value, /)
| Return self&value.
|
| bool(self, /)
| True if self else False
|
| ceil(…)
| Ceiling of an Integral returns itself.
|
| divmod(self, value, /)
…….
Python 解释器会自内而外解释help(round(-2.01))这个表达式。首先它计算了round(-2.01)的值,然后help()实际上是对round(-2.01)的输出进行操作。
(看起来好像整数有挺多可讲的,我们讲完对象、方法和属性之后,上面的输出结果应该会更容易懂一些)
round()是一个非常简单的函数,它的帮助文档也非常简短。help()处理像是print()这样更为复杂和需要配置的函数也照样很强大。不要担心下面的内容看起来很难,对于现在来说,试试看看里面能不能找出点新东西。

  1. help(print)

输出内容Help on built-in function print in module builtins:

print(…)
print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)

  1. Prints the values to a stream, or to sys.stdout by default.<br /> Optional keyword arguments:<br /> file: a file-like object (stream); defaults to the current sys.stdout.<br /> sep: string inserted between values, default a space.<br /> end: string appended after the last value, default a newline.<br /> flush: whether to forcibly flush the stream.<br />(END)<br />如果你看一下,可能会发现这样一句:

sep: string inserted between values, default a space.

意思就是print()可以接受一个叫做sep的参数,它作为两个值之间的间隔,默认是空格。

定义函数

Python 自带的(也叫内建的,builtin)很好,但我们还是需要有自己的函数,下面是一个例子:

  1. def least_difference(a, b, c):
  2. diff1 = abs(a - b)
  3. diff2 = abs(b - c)
  4. diff3 = abs(a - c)
  5. return min(diff1, diff2, diff3)

上面的代码创建了一个叫做least_difference的函数,它接受三个参数,a,b和c。
函数定义需要使用def关键字,:之后带有缩进的部分就是函数的在被调用的时候所执行的内容。
return是另一个关键字,当 Python 执行到return语句时,它就会立即退出函数,然后把return后边的内容传给调用函数的上下文(上下文是指程序的一个执行环境中的一个特定的位置)。
实际上least_difference这个函数返回的是a,b,c这三个数之间的最小距离,如果你看不太懂,可以试试用它来执行一些例子:

  1. print(
  2. least_difference(1, 10, 100),
  3. least_difference(1, 10, 10),
  4. least_difference(5, 6, 7), # Python allows trailing commas in argument lists. How nice is that?
  5. )

输出内容9 0 1
或许help()能够告诉我们一些这个函数的内容?:

  1. help(least_difference)

输出内容Help on function leastdifference in module _main:

least_difference(a, b, c)
Python 读取我们自己定义的函数时好像不太聪明,因此对于我们自己写的函数,我们可以自己来写它的描述信息(术语叫做 docstring ):

  1. def least_difference(a, b, c):
  2. """Return the smallest difference between any two numbers
  3. among a, b and c.
  4. >>> least_difference(1, 5, -5)
  5. 4
  6. """
  7. diff1 = abs(a - b)
  8. diff2 = abs(b - c)
  9. diff3 = abs(a - c)
  10. return min(diff1, diff2, diff3)

输出内容Help on function leastdifference in module _main:

least_difference(a, b, c)
Return the smallest difference between any two numbers
among a, b and c.

  1. >>> least_difference(1, 5, -5)<br /> 4<br />(END)<br />是的,为一个函数添加 docstring 的方法就是在函数体的最开始用三个双引号扩住一段文字,这段文字最终会显示到`help()`输出中。<br />要培养一个良好的编程习惯,在编写函数时要为自己的函数添加上可读性良好的 docstring,这样方便后续的使用,也能够让别人理解自己的函数。

没有返回值的函数

如果一个函数不带有return语句,会怎样?

  1. def least_difference(a, b, c):
  2. """Return the smallest difference between any two numbers
  3. among a, b and c.
  4. """
  5. diff1 = abs(a - b)
  6. diff2 = abs(b - c)
  7. diff3 = abs(a - c)
  8. min(diff1, diff2, diff3)
  9. print(
  10. least_difference(1, 10, 100),
  11. least_difference(1, 10, 10),
  12. least_difference(5, 6, 7),
  13. )

输出内容None None None
Python 允许我们定义这样的函数。这种函数的调用结果是特殊值None,这类似于其他语言中的null
如果没有return语句,least_difference()似乎完全没有意义,但是有的函数可以利用“没有返回值”这个副作用来做一些有用的事情。我们已经知道print()这个函数并没有返回值(看下面代码块),但是却会在控制台上显示信息,这就是它们的“副作用”。还有一些常用的“副作用”,比如往文件中写入内容,或者对输入做一些变换。

  1. print(print())

输出内容None

默认参数

刚刚我们help(print)的时候提到了sep这个参数,它的默认值是 ,我们现在试试指定一个间隔字符:

  1. print(1,2,3, sep='< ')

输出内容1<2<3
如果不指定一个值

  1. print(1,2,3)

输出内容1 2 3
而我们为自己的函数添加默认参数也非常容易,只需要在def时为参数赋一个值即可:

  1. def greet(who="Colin"):
  2. print("Hello,", who)
  3. greet()
  4. greet(who="Kaggle")
  5. # (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
  6. greet("world")

输出内容Hello, Colin
Hello, Kaggle
Hello, world

函数作为参数

这可能有点抽象,但是这个功能很强大,你可以把一个函数作为参数传给另一个函数,先来看个例子:

  1. def mult_by_five(x):
  2. return 5 * x
  3. def call(fn, arg):
  4. """Call fn on arg"""
  5. return fn(arg)
  6. def squared_call(fn, arg):
  7. """Call fn on the result of calling fn on arg"""
  8. return fn(fn(arg))
  9. print(
  10. call(mult_by_five, 1),
  11. squared_call(mult_by_five, 1),
  12. sep='\n', # '\n' is the newline character - it starts a new line
  13. )

输出内容5
25
这种在其他函数上操作的函数叫做“高阶函数”。短期内你可能并不会自己来写这种函数,但是 Python 中有许多自带的好用的高阶函数。
max函数就有一个例子,默认的max函数会返回传入的参数中最大值的一个。但是如果我们给它的key参数传入一个函数,它就会返回使得key(x)最大的这个参数,看下面这个例子:

  1. def mod_5(x):
  2. """Return the remainder of x after dividing by 5"""
  3. return x % 5
  4. print(
  5. 'Which number is biggest?',
  6. max(100, 51, 14),
  7. 'Which number is the biggest modulo 5?',
  8. max(100, 51, 14, key=mod_5),
  9. sep='\n',
  10. )

输出内容Which number is biggest?
100
Which number is the biggest modulo 5?
14