html网站开发语言建网站 必须学html吗
html网站开发语言,建网站 必须学html吗,网站 备案 在哪,青岛建设网站的公司Functions and Getting Help
在本课中#xff0c;我们将讨论函数#xff1a;调用它们#xff0c;定义它们#xff0c;并使用Python的内置文档查找它们。 在某些语言中#xff0c;定义函数必须要有特定的参数#xff0c;每个参数都具有特定类型。 Python函数允许更灵活。…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(Youll 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.
Youll 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()显示... 该函数的头部为absx/。 在这种情况下这告诉我们abs采用单个参数x。 正斜杠并不重要但如果你很好奇你可以在这里阅读 关于该功能的简要英文描述。
常见的陷阱当你查找函数时记得传入函数本身的名称而不是调用该函数的结果。 如果我们在调用函数abs时调用帮助会发生什么 看看下面这个例子
[3]
help(abs(-2))
Help on int object:class int(object)| int(x0) - integer| int(x, base10) - 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, base0)| 4| | Methods defined here:| | __abs__(self, /)| abs(self)| | __add__(self, value, /)| Return selfvalue.| | __and__(self, value, /)| Return selfvalue.| | __bool__(self, /)| self ! 0| | __ceil__(...)| Ceiling of an Integral returns itself.| | __divmod__(self, value, /)| Return divmod(self, value).| | __eq__(self, value, /)| Return selfvalue.| | __float__(self, /)| float(self)| | __floor__(...)| Flooring an Integral returns itself.| | __floordiv__(self, value, /)| Return self//value.| | __format__(...)| default object formatter| | __ge__(self, value, /)| Return selfvalue.| | __getattribute__(self, name, /)| Return getattr(self, name).| | __getnewargs__(...)| | __gt__(self, value, /)| Return selfvalue.| | __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 selfvalue.| | __lshift__(self, value, /)| Return selfvalue.| | __lt__(self, value, /)| Return selfvalue.| | __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, modNone, /)| Return pow(self, value, mod).| | __radd__(self, value, /)| Return valueself.| | __rand__(self, value, /)| Return valueself.| | __rdivmod__(self, value, /)| Return divmod(value, self).| | __repr__(self, /)| Return repr(self).| | __rfloordiv__(self, value, /)| Return value//self.| | __rlshift__(self, value, /)| Return valueself.| | __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, modNone, /)| Return pow(value, self, mod).| | __rrshift__(self, value, /)| Return valueself.| | __rshift__(self, value, /)| Return selfvalue.| | __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, *, signedFalse) - 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 twos complement is| used to represent the integer.| | to_bytes(...)| int.to_bytes(length, byteorder, *, signedFalse) - 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 twos 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, filesys.stdout, flushFalse)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)4diff1 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 dont 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(whoColin):print(Hello,, who)greet()
greet(whoKaggle)
# (In this case, we dont need to specify the name of the argument, because its 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 argreturn fn(arg)def squared_call(fn, arg):Call fn on the result of calling fn on argreturn 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参数传入一个函数它会返回使keyx最大的参数x。
[19]
def mod_5(x):Return the remainder of x after dividing by 5return x % 5print(Which number is biggest?,max(100, 51, 14),Which number is the biggest modulo 5?,max(100, 51, 14, keymod_5),sep\n,
)
which number is biggest?
100
Which number is the biggest modulo 5?
14
Lambda functions
如果你正在编写一个简短的函数它的主体是单行如上面的mod_5Python的lambda语法很方便。
[20]
mod_5 lambda x: x % 5# Note that we dont use the return keyword above (its 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. (Well 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, keylambda name: len(name))) # or just keylen
print(Names sorted case insensitive:, sorted(names, keylambda name: name.lower()))
Longest name is: jacques
Names sorted case insensitive: [jacques, Mia, pui-wa, Ty]
Your turn!
转到练习笔记本以获得一些使用函数和获得帮助实践练习。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/89576.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!