2、python函数和获取帮助

发布时间:2024年01月16日

调用函数、定义自己的函数以及使用Python的内置文档

你已经见过并使用了printabs等函数。但是Python还有许多其他函数,而定义自己的函数是Python编程的一个重要部分。

在这个课程中,你将学习更多关于使用和定义函数的知识。

1.获取帮助

在前面的教程中,你见过abs函数,但是如果你忘记了它是做什么的呢?

help()函数可能是你学会的最重要的Python函数之一。如果你记得如何使用help(),你就掌握了理解大多数其他函数的关键。

下面是一个示例:

In [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.
    
    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.

help()显示两个内容:

  1. 函数的头部 round(number, ndigits=None)。在这个例子中,告诉我们round()接受一个我们可以描述为number的参数。另外,我们可以选择地提供一个单独的参数,可以描述为ndigits
  2. 函数的简要英文描述。

**常见错误:**当你查找一个函数时,记得传递函数本身的名字,而不是调用该函数的结果。

如果我们在对round()函数的调用上调用help会发生什么呢?查看下面单元格的输出以了解答案。

In [2]:

help(round(-2.01))

output

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
 |  
 |  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__(self, format_spec, /)
 |      Default object formatter.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getnewargs__(self, /)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /
文章来源:https://blog.csdn.net/jiangxinufo00/article/details/135595897
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。