2.Functions and Getting Help

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!

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

 

 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/440375.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

华人科学家量子计算机,华人科学家在美国研发出性能强大的光子计算机,能够与中国的量子计算机一战高下!...

原标题&#xff1a;华人科学家在美国研发出性能强大的光子计算机&#xff0c;能够与中国的量子计算机一战高下&#xff01;在最近的《自然纳米技术》杂志上&#xff0c;一篇来自美国哥伦比亚大学的论文在业界掀起了轩然大波&#xff0c;一位名叫虞南方的物理学助理教授成功率领…

【BZOJ - 1001】狼抓兔子(无向图网络流,最小割,或平面图转对偶图求最短路SPFA)

题干&#xff1a; 现在小朋友们最喜欢的"喜羊羊与灰太狼",话说灰太狼抓羊不到&#xff0c;但抓兔子还是比较在行的&#xff0c; 而且现在的兔子还比较笨&#xff0c;它们只有两个窝&#xff0c;现在你做为狼王&#xff0c;面对下面这样一个网格的地形&#xff1a; …

3.Booleans and Conditionals

Booleans Python有bool类型数据&#xff0c;有两种取值&#xff1a;True 和 False. [1] x True print(x) print(type(x)) True <class bool> 我们通常从布尔运算符中获取布尔值&#xff0c;而不是直接在我们的代码中放入True或False。 这些是回答yes或no的运算符。…

能利用计算机来模拟某种真实的实验现象,自然现象或社会现象的课件是,《计算机辅助教学》课程复习资料...

考试资料《计算机辅助教学》课程复习资料一、单项选择题1. 教学软件又称为 A 。A.课件 B.多媒体 C.操作系统 D.应用软件2. 继课件之后的第二代教学软件称为 A 。A积件 B.课件 C.网络课件 D.智能型课件3. 建构主义学习理论强调认知主体是 B 。A. 教师 B. 学习者 C. 教务 D. 辅导…

【洛谷 - P3376 】【模板】网络最大流

题干&#xff1a; 如题&#xff0c;给出一个网络图&#xff0c;以及其源点和汇点&#xff0c;求出其网络最大流。 输入输出格式 输入格式&#xff1a; 第一行包含四个正整数N、M、S、T&#xff0c;分别表示点的个数、有向边的个数、源点序号、汇点序号。 接下来M行每行包含…

4.Lists

Lists Python中的列表表示有序的值。 可以使用方括号来定义&#xff0c;变量值之间用逗号隔开。 例如&#xff0c;这是几个素数的列表&#xff1a; [1] primes [2, 3, 5, 7] 我们可以将其他类型的东西放在列表中&#xff1a; [2] planets [Mercury, Venus, Earth, Mars…

怎么用计算机拟合数据,数据拟合的几个应用实例-毕业论文.doc

本科毕业设计(论文)数据拟合的几个使用实例燕 山 大 学年 月本科毕业设计(论文)数据拟合的几个使用实例学 院&#xff1a;专 业&#xff1a;学生姓名&#xff1a;学 号&#xff1a;指导教师&#xff1a;答辩日期&#xff1a;燕山大学毕业设计任务书学院&#xff1a; 系级教学单…

1.UNIX网络编程卷1:源码配置

本节主要介绍UNIX网络编程卷1&#xff08;第三版&#xff09;在Ubuntu16.04的配置问题&#xff0c;并运行一个简单时间获取客户程序。 1.首先下载源文件&#xff0c;链接如下&#xff1a;UNIX Network Programming Source Code 2.将下载好的压缩文件unpv13e.tar.gz解压&#…

【牛客 - 696C】小w的禁忌与小G的长诗(dp 或 推公式容斥)

题干&#xff1a; 链接&#xff1a;https://ac.nowcoder.com/acm/contest/696/C 来源&#xff1a;牛客网 自从上次小w被奶牛踹了之后&#xff0c;就一直对此耿耿于怀。 于是"cow"成为了小w的禁忌&#xff0c;而长得和"cow"很像的"owc"…凡是…

html 地球大气,地球大气层为什么永远不会消失?

地球的大气层是一个很神奇的存在&#xff0c;几十亿年来&#xff0c;它就如同一层厚厚的保护膜&#xff0c;将地球与太空完全阻隔起来&#xff0c;正因为如此&#xff0c;地球上的生命才能够繁衍生息&#xff0c;代代相传。相信很多人都会有这样的疑问&#xff0c;为什么地球上…

5.Loops and List Comprehensions

Loops 循环是一种重复执行某些代码的方法。 [1] planets [Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune] for planet in planets:print(planet, end ) # print all on same line Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 注意for循环…

【牛客 - 696D】小K的雕塑(dp,鸽巢原理,01背包类问题)

题干&#xff1a; 链接&#xff1a;https://ac.nowcoder.com/acm/contest/696/D 来源&#xff1a;牛客网 小K有n个雕塑&#xff0c;每个雕塑上有一个整数 若集合T中的每一个元素在n个雕塑上都能找得到&#xff0c;则称这个集合为一个优秀的集合 小K想知道所有大小<k优秀…

计算机专业需要汇编语言,重点大学计算机专业系列教材·汇编语言程序设计

重点大学计算机专业系列教材汇编语言程序设计语音编辑锁定讨论上传视频本词条缺少概述图&#xff0c;补充相关内容使词条更完整&#xff0c;还能快速升级&#xff0c;赶紧来编辑吧&#xff01;《重点大学计算机专业系列教材汇编语言程序设计》是2009年10月1日清华大学出版社出版…

6.Strings and Dictionaries

目录 Strings 1. String syntax 2、Strings are sequences 3、String methods Strings Python语言真正发挥作用的一个地方是字符串的操作。 本节将介绍Python的一些内置字符串方法和格式化操作。 这种字符串操作模式经常出现在数据科学工作中&#xff0c;并且在这种情况下…

【LightOJ - 1123】Trail Maintenance(在线维护最小生成树,删边思维)

题干&#xff1a; Tigers in the Sunderbans wish to travel freely among the N fields (numbered from 1 to N), even though they are separated by trees. The tigers wish to maintain trails between pairs of fields so that they can travel from any field to any ot…

7.Working with External Libraries

在本课中&#xff0c;我将讨论Python中的imports&#xff0c;提供一些使用不熟悉的库&#xff08;以及它们返回的对象&#xff09;的技巧&#xff0c;并深入研究Python的内容&#xff0c;以及谈谈运算符重载。 Imports 到目前为止&#xff0c;我们已经讨论了内置于该语言的类…

计算机原理期中考试,计算机组成原理期中考试试题

一、单选题(每小题2分&#xff0c;共34分)1&#xff0e;完整的计算机系统应包括__________。A&#xff0e;运算器、存储器、控制器 B&#xff0e; 主机和实用程序C&#xff0e;配套的硬件设备和软件系统 D&#xff0e; 外部设备和主机2&#xff0e;下列数中真值最小的数是_____…

【HDU - 1839】Delay Constrained Maximum Capacity Path(最短路 + 二分)

题干&#xff1a; 考虑一个包含 N 个顶点的无向图&#xff0c;编号从 1 到 N&#xff0c;并包含 M 条边。编号为 1 的顶点对应了一个矿藏&#xff0c;可从中提取珍稀的矿石。编号为 N 的顶点对应了一个矿石加工厂。每条边有相应的通行时间 (以时间单位计)&#xff0c;以及相应…

0.Overview

本文为Kaggle Learn的Python课程的中文翻译&#xff0c;原文链接为&#xff1a;https://www.kaggle.com/learn/python 欢迎来到Kaggle Learn的Python课程。本课程将介绍在开始使用Python进行数据科学之前需要的基本Python技能。这些课程针对那些具有一些编程经验的人&#xff…

量子计算机的体积有多大,量子计算机也能实现摩尔定律

原标题&#xff1a;量子计算机也能实现摩尔定律量子计算机拥有很强大的计算力&#xff0c;但是这对IBM来说&#xff0c;似乎还不够。据CNET消息&#xff0c;IBM制作了一个路线图&#xff0c;表达出了自己在量子计算领域的野心。IBM在图表的纵轴上列出了一个单位“量子体积(Quan…