文章目录
- 概述
- 寻求帮助(getting help)
- 定义函数(Defining functions)
- Docstrings
- Functions that don't return(定义一个不包含return的方程)
- 默认参数(Default argument)
- Functions Applied to Functions(函数在函数中的应用)
- pass
- round
概述
Python中有很多函数,我们在上节学习了print
和abs
等内置函数。
而自定义函数也是Python中非常重要的部分。本节主要学习了函数的定义和使用。
寻求帮助(getting help)
当我们忘记一个函数的用法时,help()
函数能帮助我们理解其他的函数。
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.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
ndigits如果不等于None或者没被省略,roungd返回的类型就是,与ndigits规定的数字有关。
'''
help()
呈现两部分结果
- 函数的标头,在这个例子中是
round(number[, ndigits])
,它告诉我们round
函数接收一个number
,另外我们可以选择行的给出一个不同的参数ndigits
。(ndigits
在这里表示小数点后几位) - 关于方程功能的简单描述。
常见陷阱 :当我们查询函数的时候,要查询函数的名字abs
,而不是函数的调用(calling that function)abs()
。
help(round(-2.01))
# 结果显示了很多关于整数的内容
Python计算一个表达式是由内而外计算的。所以上面的表达式中,先计算round(-2.01)
,然后查询(help)round(-2.01)
的结果(output of that expression)。
round
函数是一个具有简短文档字符串(DocStrings)的简单函数。在之后的学习中,我们会处理一些更复杂和可配置的(configurable)函数,好比print
。当遇到一些难以理解的(inscrutable)文档字符串的时候,我们要学会从中提取一些新的知识。
help(print)
'''
Help on built-in function print in module builtins(模块内置命令):
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
'''
我们可以看出print
函数可以接受一个变量sep
,他表示当我们print
其他变量时,放置在变量件的东西。
定义函数(Defining functions)
def least_difference(a, b, c):
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
上面模块中定义了函数least_difference
,他有三个参数 a
, b
, 和c
。
定义函数以def
为标头,缩进模块(indented block)跟在:
后。return
是与函数唯一关联的另一个关键字。当Python遇到return
语句时,立即退出函数,并将return
右边的值调用于上下文中。
例子:
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
# 9 0 1
另外,我们可以尝试用help
函数解释我们定义least_difference
:
help(least_difference)
'''
Help on function least_difference in module __main__:
least_difference(a, b, c)
'''
由上述代码可以看出Python不足够聪明给我定义的函数一个合理的解释。所以当我们在定义一个函数后,我们可以为这个函数提供一个描述,叫做docstring(文档字符串)。
Docstrings
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
return min(diff1, diff2, diff3)
定义函数中的文档字符串是一个三引号字符串(它可以由很多行组成),它的位置是在函数标头(header)下的第一行开始。
当我们调用help
函数时,结果展示文档字符串。
help(least_difference)
'''
least_difference(a, b, c)
Return the smallest difference between any two numbers
among a, b and c.
>>> least_difference(1, 5, -5)
4
'''
The
>>>
is a reference to the command prompt(命令提示符) used in Python interactive shells.
The example in docstrings help someone understand the function.
优秀的程序员都会使用文档字符串,除非这个方程在之后会被丢掉。
Functions that don’t return(定义一个不包含return的方程)
当我们在定义方程时,不加入return
,会发生什么呢?
def least_difference(a, b, c):
"""Return the smallest difference between any two numbers
among a, b and c.
"""
diff1 = abs(a - b)
diff2 = abs(b - c)
diff3 = abs(a - c)
min(diff1, diff2, diff3)
print(
least_difference(1, 10, 100),
least_difference(1, 10, 10),
least_difference(5, 6, 7),
)
# 结果:None None None
- Python 允许我们定义不包括
return
的函数,调用函数显示None
(这与其他函数中的‘null’ 相似)。 - 没有
return
的函数least_difference
毫无意义;但当定义函数不包括return
在一些情况下也是有用的。我们仅仅调用无return
的函数,来输出一些文本,或者还可以写入文件(writing to a file)和调节输入(modifying an input)。
least_difference()
'''
返回结果报错:
--------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-1fd5223251aa> in <module>
----> 1 least_difference()
TypeError: least_difference() missing 3 required positional arguments: 'a', 'b', and 'c'
'''
mystery = print()
print(mystery)
# 返回结果:None
默认参数(Default argument)
当我们在调用help(print)
时,我们可以看到print
函数有一些可选择的参数(optional arguments)。例如,我们可以为sep
指定一个值(specify a value)。
print(1, 2, 3, sep=' < ')
# 1 < 2 < 3
但是当我们不为sep
指定一个值的时候,sep
被处理为有一个默认值’ '(a single space)
print(1, 2, 3)
# 1 2 3
增加一个存在默认值的参数:
def greet(who="Colin"):
print("Hello,", who)
greet()
greet(who="Kaggle")
# (In this case, we don't need to specify the name of the argument, because it's unambiguous.)
greet("world")
'''
Hello, Colin
Hello, Kaggle
Hello, world
'''
Functions Applied to Functions(函数在函数中的应用)
我们可以将函数作为参数提供给其他函数。
def mult_by_five(x):
return 5 * x
def call(fn, arg):
"""Call fn on arg"""
return fn(arg)
def squared_call(fn, arg):
"""Call fn on the result of calling fn on arg"""
return fn(fn(arg))
print(
call(mult_by_five, 1),
squared_call(mult_by_five, 1),
sep='\n', # '\n' is the newline character - it starts a new line
)
# 5
# 25
-
\n
换行字符 -
max
函数在加入key
后又名argmax
(aka the ‘argmax’) - aka: also know as 又名
def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5
print(
'Which number is biggest?',
max(100, 51, 14),
'Which number is the biggest modulo 5?',
max(100, 51, 14, key=mod_5),
sep='\n',
)
'''
Which number is biggest?
100
Which number is the biggest modulo 5?
14
'''
pass
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code block, Python requires at least one line of code)
pass
pass
在函数中没有作用,我们使用它作为一个占位符(placeholder),因为在我们开始一个代码块,Python需要至少一行的代码。
round
round()
函数中,当ndigits = -1, -2 … 负数时,number被round
到最近的10, 100…
round(123.12, ndigits = -1)
# 120.0
The area of Finland is 338,424 km²
The area of Greenland is 2,166,086 km²当ndigits = -3
The area of Finland is 338,000 km²
The area of Greenland is 2,166,000 km²
round()
函数中,当ndigits = -1, -2 … 负数时,number被round
到最近的10, 100…
round(123.12, ndigits = -1)
# 120.0
The area of Finland is 338,424 km²
The area of Greenland is 2,166,086 km²当ndigits = -3
The area of Finland is 338,000 km²
The area of Greenland is 2,166,000 km²