Functions and Getting Help

在本课中,我们将讨论函数:调用它们,定义它们,并使用Python的内置文档查找它们。
在某些语言中,定义函数必须要有特定的参数,每个参数都具有特定类型。 Python函数允许更灵活。 print函数就是一个很好的例子:

[1]

print("The print function takes an input and prints it to the screen.")
print("Each call to print starts on a new line.")
print("You'll often call print with strings, but you can pass any kind of value. For example, a number:")
print(2 + 2)
print("If print is called with multiple arguments...", "it joins them","(with spaces in between)", "before printing.")
print('But', 'this', 'is', 'configurable', sep='!...')
print()
print("^^^ print can also be called with no arguments to print a blank line.")
The print function takes an input and prints it to the screen.
Each call to print starts on a new line.
You'll often call print with strings, but you can pass any kind of value. For example, a number:
4
If print is called with multiple arguments... it joins them (with spaces in between) before printing.
But!...this!...is!...configurable^^^ print can also be called with no arguments to print a blank line.

"What does this function do again?"

在前面的章节中我已经介绍了abs函数,但是如果你忘了它的作用怎么办?

help()函数可能是你学习的最重要的Python函数。 如果你能记住如何使用help(),那么你就掌握了解Python中任何其他函数。

[2]

help(abs)
Help on built-in function abs in module builtins:abs(x, /)Return the absolute value of the argument.

应用于函数时,help()显示...

  • 该函数的头部为abs(x,/)。 在这种情况下,这告诉我们abs()采用单个参数x。 (正斜杠并不重要,但如果你很好奇,你可以在这里阅读)
  • 关于该功能的简要英文描述。

常见的陷阱:当你查找函数时,记得传入函数本身的名称,而不是调用该函数的结果。

如果我们在调用函数abs()时调用帮助会发生什么? 看看下面这个例子:

[3]

help(abs(-2))
Help on int object:class int(object)|  int(x=0) -> 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|  |  Methods defined here:|  |  __abs__(self, /)|      abs(self)|  |  __add__(self, value, /)|      Return self+value.|  |  __and__(self, value, /)|      Return self&value.|  |  __bool__(self, /)|      self != 0|  |  __ceil__(...)|      Ceiling of an Integral returns itself.|  |  __divmod__(self, value, /)|      Return divmod(self, value).|  |  __eq__(self, value, /)|      Return self==value.|  |  __float__(self, /)|      float(self)|  |  __floor__(...)|      Flooring an Integral returns itself.|  |  __floordiv__(self, value, /)|      Return self//value.|  |  __format__(...)|      default object formatter|  |  __ge__(self, value, /)|      Return self>=value.|  |  __getattribute__(self, name, /)|      Return getattr(self, name).|  |  __getnewargs__(...)|  |  __gt__(self, value, /)|      Return self>value.|  |  __hash__(self, /)|      Return hash(self).|  |  __index__(self, /)|      Return self converted to an integer, if self is suitable for use as an index into a list.|  |  __int__(self, /)|      int(self)|  |  __invert__(self, /)|      ~self|  |  __le__(self, value, /)|      Return self<=value.|  |  __lshift__(self, value, /)|      Return self<<value.|  |  __lt__(self, value, /)|      Return self<value.|  |  __mod__(self, value, /)|      Return self%value.|  |  __mul__(self, value, /)|      Return self*value.|  |  __ne__(self, value, /)|      Return self!=value.|  |  __neg__(self, /)|      -self|  |  __new__(*args, **kwargs) from builtins.type|      Create and return a new object.  See help(type) for accurate signature.|  |  __or__(self, value, /)|      Return self|value.|  |  __pos__(self, /)|      +self|  |  __pow__(self, value, mod=None, /)|      Return pow(self, value, mod).|  |  __radd__(self, value, /)|      Return value+self.|  |  __rand__(self, value, /)|      Return value&self.|  |  __rdivmod__(self, value, /)|      Return divmod(value, self).|  |  __repr__(self, /)|      Return repr(self).|  |  __rfloordiv__(self, value, /)|      Return value//self.|  |  __rlshift__(self, value, /)|      Return value<<self.|  |  __rmod__(self, value, /)|      Return value%self.|  |  __rmul__(self, value, /)|      Return value*self.|  |  __ror__(self, value, /)|      Return value|self.|  |  __round__(...)|      Rounding an Integral returns itself.|      Rounding with an ndigits argument also returns an integer.|  |  __rpow__(self, value, mod=None, /)|      Return pow(value, self, mod).|  |  __rrshift__(self, value, /)|      Return value>>self.|  |  __rshift__(self, value, /)|      Return self>>value.|  |  __rsub__(self, value, /)|      Return value-self.|  |  __rtruediv__(self, value, /)|      Return value/self.|  |  __rxor__(self, value, /)|      Return value^self.|  |  __sizeof__(...)|      Returns size in memory, in bytes|  |  __str__(self, /)|      Return str(self).|  |  __sub__(self, value, /)|      Return self-value.|  |  __truediv__(self, value, /)|      Return self/value.|  |  __trunc__(...)|      Truncating an Integral returns itself.|  |  __xor__(self, value, /)|      Return self^value.|  |  bit_length(...)|      int.bit_length() -> int|      |      Number of bits necessary to represent self in binary.|      >>> bin(37)|      '0b100101'|      >>> (37).bit_length()|      6|  |  conjugate(...)|      Returns self, the complex conjugate of any int.|  |  from_bytes(...) from builtins.type|      int.from_bytes(bytes, byteorder, *, signed=False) -> int|      |      Return the integer represented by the given array of bytes.|      |      The bytes argument must be a bytes-like object (e.g. bytes or bytearray).|      |      The byteorder argument determines the byte order used to represent the|      integer.  If byteorder is 'big', the most significant byte is at the|      beginning of the byte array.  If byteorder is 'little', the most|      significant byte is at the end of the byte array.  To request the native|      byte order of the host system, use `sys.byteorder' as the byte order value.|      |      The signed keyword-only argument indicates whether two's complement is|      used to represent the integer.|  |  to_bytes(...)|      int.to_bytes(length, byteorder, *, signed=False) -> bytes|      |      Return an array of bytes representing an integer.|      |      The integer is represented using length bytes.  An OverflowError is|      raised if the integer is not representable with the given number of|      bytes.|      |      The byteorder argument determines the byte order used to represent the|      integer.  If byteorder is 'big', the most significant byte is at the|      beginning of the byte array.  If byteorder is 'little', the most|      significant byte is at the end of the byte array.  To request the native|      byte order of the host system, use `sys.byteorder' as the byte order value.|      |      The signed keyword-only argument determines whether two's complement is|      used to represent the integer.  If signed is False and a negative integer|      is given, an OverflowError is raised.|  |  ----------------------------------------------------------------------|  Data descriptors defined here:|  |  denominator|      the denominator of a rational number in lowest terms|  |  imag|      the imaginary part of a complex number|  |  numerator|      the numerator of a rational number in lowest terms|  |  real|      the real part of a complex number

Python从内到外评估这样的表达式。 首先,它计算abs(-2)的值,然后它提供有关该表达式的任何值的帮助。
(事实证明有很多关于整数的说法!在Python中,即使是简单的东西, 看起来像一个整数实际上也是一个具有相当大内部复杂性的对象。在稍后我们将讨论Python中的对象,方法和属性,上面的大量帮助输出会更有意义。)

[4]

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.

其中一些可能看起来不可思议(什么是sys.stdout?),但是这个docstring确实揭示了我们在开头的一个打印示例中使用的sep参数。

Defining functions

内置函数非常棒,但在我们需要定义自己的函数之前,我们只能使用它们。 下面是一个简单的定义函数的例子。

[5]

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关键字开头。 调用函数时会运行冒号后面: 的缩进代码块。
return是与函数唯一关联的另一个关键字。 当Python遇到return语句时,它会立即退出函数,并将右侧的值传递给调用上下文。
是否清楚了源码中的least_difference()做了什么? 如果我们不确定,我们总是可以尝试一些例子:

[6]

print(least_difference(1, 10, 100),least_difference(1, 10, 100),least_difference(5, 6, 7),#Python允许在参数列表中使用尾随逗号,很有趣吧?
)
9 0 1

或许help()函数可以告诉我们一些事情。

[7]

hep(least_difference)
Help on function least_difference in module __main__:least_difference(a, b, c)

不出所料,Python不够聪明,无法读取我的代码并将其变成一个很好的英文描述。 但是,当我编写一个函数时,我可以提供一个名为docstring的描述。

Docsting(文档字符串)

[8]

def least_difference(a, b, c):"""Return the smallest difference between any two numbersamong 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)

docstring是一个三引号""""""字符串(可能跨越多行),紧跟在函数头之后。 当我们在函数上调用help()时,它会显示docstring。

[9]

help(least_difference)
Help on function least_difference in module __main__:least_difference(a, b, c)Return the smallest difference between any two numbersamong a, b and c.>>> least_difference(1, 5, -5)4

旁白:示例调用 docstring的最后两行是示例函数调用和结果。 (>>>是对Python交互式shell中使用的命令提示符的引用。)Python不运行示例调用 - 它只是为了读者的利益。 在函数的文档字符串中包含一个或多个示例调用的约定远非普遍观察到,但它可以非常有效地帮助某人理解您的函数。 有关实际示例,请参阅numpy函数的docstring。

Docstrings是一种很好的方式来他人介绍你的代码,甚至是你自己。 (你有多少次回到你前一天工作的一些代码,并想知道“我在想什么?”)

Functions that don't return

如果在函数中不包含return关键字会怎么样?

[10]

def least_difference(a, b, c):"""Return the smallest difference between any two numbersamong 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允许我们定义这样的函数。 调用它们的结果是特殊值None。 (这与其他语言中的“null”概念类似。)
没有return语句,least_difference是完全没有意义的,但是带有副作用的函数可以在不返回任何内容的情况下做一些有用的事情。 我们已经看到了两个这样的例子:print()和help()不返回任何内容。 我们调用它们只是为了副作用(在屏幕上放置一些文字)。 其他有用的副作用示例包括写入文件或修改输入。

[11]

mystery = print()
print(mystery)
None

Default arguments

当我们调用help(print)时,我们看到print函数有一些可选参数,例如,我们可以为sep指定一个值,在我们打印的参数之间添加一些特殊字符串:

[12]

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

但是如果我们不指定sep的值,sep默认值是空格' '。

[13]

print(1, 2, 3)1 2 3

将可选参数的默认值添加到我们定义的函数中非常简单:

[14]

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 are objects too

[15]

def f(n):return n * 2x = 12.5

创建它们的语法可能不同,但上面代码中的f和x并没有根本不同。 它们是每个对象的引用变量。 x指的是float类型的对象,f指的是......’类型的对象好吧,让我们问Python:

[16]

print(type(x),type(f), sep='\n'
)
<class 'float'>
<class 'function'>

我们甚至可以让Python打印出f:

[17]

print(x)
print(f)12.5
<function f at 0x7fbdb18040d0>

......虽然它显示的并不是非常有用。
请注意,上面的代码单元有将另一个函数作为输入的函数(type and print)的示例。 这开辟了一些有趣的可能性 - 我们可以将我们收到的函数作为参数调用。

[18]

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(f, 1),squared_call(f, 1), sep='\n', # '\n' is the newline character - it starts a new line
)
2
4

您可能不会经常自己定义更高阶的函数,但是有一些现有的函数(内置于Python和像pandas或numpy这样的库中),您可能会发现这些函数很有用。 例如,max函数。
默认情况下,max返回其最大的参数。 但是如果我们使用可选的key参数传入一个函数,它会返回使key(x)最大的参数x。

[19]

def mod_5(x):"""Return the remainder of x after dividing by 5"""return x % 5print('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

Lambda functions

如果你正在编写一个简短的函数,它的主体是单行(如上面的mod_5),Python的lambda语法很方便。

[20]

mod_5 = lambda x: x % 5# Note that we don't use the "return" keyword above (it's implicit)
# (The line below would produce a SyntaxError)
#mod_5 = lambda x: return x % 5print('101 mod 5 =', mod_5(101))
101 mod 5 = 1

[21]

# Lambdas can take multiple comma-separated arguments
abs_diff = lambda a, b: abs(a-b)
print("Absolute difference of 5 and 7 is", abs_diff(5, 7))
Absolute difference of 5 and 7 is 2

[23]

# Or no arguments
always_32 = lambda: 32
always_32()32

通过明智地使用lambdas,您可以偶尔在一行中解决复杂问题。

[23]

# Preview of lists and strings. (We'll go in depth into both soon)
# - len: return the length of a sequence (such as a string or list)
# - sorted: return a sorted version of the given sequence (optional key
#           function works similarly to max and min)
# - s.lower() : return a lowercase version of string s
names = ['jacques', 'Ty', 'Mia', 'pui-wa']
print("Longest name is:", max(names, key=lambda name: len(name))) # or just key=len
print("Names sorted case insensitive:", sorted(names, key=lambda name: name.lower()))
Longest name is: jacques
Names sorted case insensitive: ['jacques', 'Mia', 'pui-wa', 'Ty']

Your turn!

转到练习笔记本,以获得一些使用函数和获得帮助实践练习。

2.Functions and Getting Help相关推荐

  1. Scala:Functions and Closures

    1 object Functions { 2 def main(args: Array[String]) { 3 // 本地函数 4 def localFun(msg: String) = print ...

  2. JAVA Functions in XI(转)

    1. String [ ] StrArray = LGORT.split(",") //-- pass LGORT to this UDF           int len1 = ...

  3. fcm和firebase_我如何最终使Netlify Functions,Firebase和GraphQL一起工作

    fcm和firebase In a previous post I confessed defeat in attempting to get an AWS Lambda GraphQL server ...

  4. Oracle 聚合函数(Aggregate Functions)说明

    Oracle Aggregate Functions用过很多,官网的说明如下: Aggregate Functions http://docs.oracle.com/cd/E11882_01/serv ...

  5. Analytic Functions 分析函数(rank over)

    此篇文章是为了学会rank() over()所写. 官方文档 (DENSE_)RANK( ) OVER ([ query_partition_clause ] order_by_clause) ran ...

  6. 2017 多校3 hdu 6061 RXD and functions

    2017 多校3 hdu 6061 RXD and functions(FFT) 题意: 给一个函数\(f(x)=\sum_{i=0}^{n}c_i \cdot x^{i}\) 求\(g(x) = f ...

  7. R语言笔记6:在R中写一些简单的函数、functions基础和作用域

    R语言基础系列: 1数据类型(向量.数组.矩阵. 列表和数据框) 2读写数据所需的主要函数.与外部环境交互 3数据筛选--提取对象的子集 4向量.矩阵的数学运算 5控制结构 Your first R ...

  8. 微软宣布Azure Functions正式支持Java

    微软宣布Azure Functions V2.0支持Java.开发人员现在可以用Java 8编写Function,并利用Visual Studio Code.IntelliJ.Eclipse和跨平台F ...

  9. SAP Explore hidden functions in MD04

    MD04 has many hidden powerful and useful functions. Knowing them could make our daily work easier to ...

  10. Kotlin functions

    2019独角兽企业重金招聘Python工程师标准>>> Kotlin functions fun hello() { println("hello world") ...

最新文章

  1. 谷歌研究院最新发现:训练结果不准确,超大数据规模要背锅!
  2. Android问题-DelphiXE5编义时提示找不到“连接器(arm-linux-androideabi-ld.exe)
  3. sql server 常用函数
  4. python编程入门书-关于 Python 的经典入门书籍有哪些?
  5. 分布式工具的一次小升级⏫
  6. emmc boot1 boot2 partition
  7. Java yield详解_Java 中的 yield 关键字
  8. 在Python中用turtle函数画同心圆
  9. 关于 redis、memcache、mongoDB 的对比
  10. java单列_Java 单例模式
  11. Java笔记04-核心类库
  12. 10张图22段代码,万字长文带你搞懂虚拟内存模型和malloc内部原理
  13. 物理学基石 —— 麦克斯韦方程组
  14. python和c语言的区别-C语言、Java语言和python语言的区别在哪里
  15. WebSocket刷新断开原因、设计心跳机制防止自动断开连接
  16. 数据分析软件及spss简单操作
  17. latch: cache buffers chains问题分析
  18. 任何情况下请通过正规渠道变更信用卡额度
  19. Android 手机遥控器控制机顶盒(电视)
  20. java 判断是否回文

热门文章

  1. 分割法和填补法_“聚合”法与“分割”法
  2. java web.xml 监听器_【JAVA 核心技术】java web 中的监听器
  3. 审计署计算机培训心得体会,审计署计算机中级培训心得体会2018
  4. android 交叉编译so,Android交叉编译htop和使用方法
  5. c语言链表编程作业,C语言编程入门——链表
  6. OpenGL 4.0 Tutorials 第三章:初始化 OpenGL 4.0
  7. linux+qt+定时精度,Qt QTimer测试定时精度
  8. linux suse11 nfs,suse11 nfsserver服务安装
  9. java 图形处理库_java中处理图片的类库
  10. hive sql 怎么实现循环_Hive存储过程实现-hpsql