1.3.2 常用内置函数

Posted Avention

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.3.2 常用内置函数相关的知识,希望对你有一定的参考价值。

  常用内置函数(Built-In Functions,BIF)不需要导入任何模块即可直接使用,在IDLE中执行如下命令可以列出所有内置函数和内置对象,如代码块1.3.2.1所示:

1 >>> dir(__builtins__)
2 [\'ArithmeticError\', \'AssertionError\', \'AttributeError\', \'BaseException\', \'BlockingIOError\', \'BrokenPipeError\', \'BufferError\',
\'BytesWarning\', \'ChildProcessError\', \'ConnectionAbortedError\', \'ConnectionError\', \'ConnectionRefusedError\', \'ConnectionResetError\',
\'DeprecationWarning\', \'EOFError\', \'Ellipsis\', \'EnvironmentError\', \'Exception\', \'False\', \'FileExistsError\', \'FileNotFoundError\',
\'FloatingPointError\', \'FutureWarning\', \'GeneratorExit\', \'IOError\', \'ImportError\', \'ImportWarning\', \'IndentationError\', \'IndexError\',
\'InterruptedError\', \'IsADirectoryError\', \'KeyError\', \'KeyboardInterrupt\', \'LookupError\', \'MemoryError\', \'NameError\', \'None\',
\'NotADirectoryError\', \'NotImplemented\', \'NotImplementedError\', \'OSError\', \'OverflowError\', \'PendingDeprecationWarning\',
\'PermissionError\', \'ProcessLookupError\', \'RecursionError\', \'ReferenceError\', \'ResourceWarning\', \'RuntimeError\', \'RuntimeWarning\',
\'StopAsyncIteration\', \'StopIteration\', \'SyntaxError\', \'SyntaxWarning\', \'SystemError\', \'SystemExit\', \'TabError\', \'TimeoutError\', \'True\',
\'TypeError\', \'UnboundLocalError\', \'UnicodeDecodeError\', \'UnicodeEncodeError\', \'UnicodeError\', \'UnicodeTranslateError\', \'UnicodeWarning\',
\'UserWarning\', \'ValueError\', \'Warning\', \'WindowsError\', \'ZeroDivisionError\', \'__build_class__\', \'__debug__\', \'__doc__\', \'__import__\',
\'__loader__\', \'__name__\', \'__package__\', \'__spec__\', \'abs\', \'all\', \'any\', \'ascii\', \'bin\', \'bool\', \'bytearray\', \'bytes\',
\'callable\', \'chr\', \'classmethod\', \'compile\', \'complex\', \'copyright\', \'credits\', \'delattr\', \'dict\', \'dir\', \'divmod\',
\'enumerate\', \'eval\', \'exec\', \'exit\', \'filter\', \'float\', \'format\', \'frozenset\', \'getattr\', \'globals\', \'hasattr\',
\'hash\', \'help\', \'hex\', \'id\', \'input\', \'int\', \'isinstance\', \'issubclass\', \'iter\', \'len\', \'license\', \'list\', \'locals\', \'map\',
\'max\', \'memoryview\', \'min\', \'next\', \'object\', \'oct\', \'open\', \'ord\', \'pow\', \'print\', \'property\', \'quit\', \'range\', \'repr\',
\'reversed\', \'round\', \'set\', \'setattr\', \'slice\', \'sorted\', \'staticmethod\', \'str\', \'sum\', \'super\', \'tuple\', \'type\', \'vars\', \'zip\'] 3 >>>

                              代码块1.3.2.1

  可以使用 help(函数名) 查看某个函数的用法,不需要导入模块就可以直接使用 help(模块名)查看该模块的帮助文档,例如 help(\'math\')。help()函数示例,参考代码块1.3.2.2

  1 >>> help(abs)
  2 Help on built-in function abs in module builtins:
  3 
  4 abs(x, /)
  5     Return the absolute value of the argument.
  6 
  7 >>> 
  8 >>> 
  9 >>> help(math)
 10 Traceback (most recent call last):
 11   File "<pyshell#8>", line 1, in <module>
 12     help(math)
 13 NameError: name \'math\' is not defined
 14 >>> 
 15 >>> help(\'math\')
 16 Help on built-in module math:
 17 
 18 NAME
 19     math
 20 
 21 DESCRIPTION
 22     This module is always available.  It provides access to the
 23     mathematical functions defined by the C standard.
 24 
 25 FUNCTIONS
 26     acos(...)
 27         acos(x)
 28         
 29         Return the arc cosine (measured in radians) of x.
 30     
 31     acosh(...)
 32         acosh(x)
 33         
 34         Return the inverse hyperbolic cosine of x.
 35     
 36     asin(...)
 37         asin(x)
 38         
 39         Return the arc sine (measured in radians) of x.
 40     
 41     asinh(...)
 42         asinh(x)
 43         
 44         Return the inverse hyperbolic sine of x.
 45     
 46     atan(...)
 47         atan(x)
 48         
 49         Return the arc tangent (measured in radians) of x.
 50     
 51     atan2(...)
 52         atan2(y, x)
 53         
 54         Return the arc tangent (measured in radians) of y/x.
 55         Unlike atan(y/x), the signs of both x and y are considered.
 56     
 57     atanh(...)
 58         atanh(x)
 59         
 60         Return the inverse hyperbolic tangent of x.
 61     
 62     ceil(...)
 63         ceil(x)
 64         
 65         Return the ceiling of x as an Integral.
 66         This is the smallest integer >= x.
 67     
 68     copysign(...)
 69         copysign(x, y)
 70         
 71         Return a float with the magnitude (absolute value) of x but the sign 
 72         of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
 73         returns -1.0.
 74     
 75     cos(...)
 76         cos(x)
 77         
 78         Return the cosine of x (measured in radians).
 79     
 80     cosh(...)
 81         cosh(x)
 82         
 83         Return the hyperbolic cosine of x.
 84     
 85     degrees(...)
 86         degrees(x)
 87         
 88         Convert angle x from radians to degrees.
 89     
 90     erf(...)
 91         erf(x)
 92         
 93         Error function at x.
 94     
 95     erfc(...)
 96         erfc(x)
 97         
 98         Complementary error function at x.
 99     
100     exp(...)
101         exp(x)
102         
103         Return e raised to the power of x.
104     
105     expm1(...)
106         expm1(x)
107         
108         Return exp(x)-1.
109         This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
110     
111     fabs(...)
112         fabs(x)
113         
114         Return the absolute value of the float x.
115     
116     factorial(...)
117         factorial(x) -> Integral
118         
119         Find x!. Raise a ValueError if x is negative or non-integral.
120     
121     floor(...)
122         floor(x)
123         
124         Return the floor of x as an Integral.
125         This is the largest integer <= x.
126     
127     fmod(...)
128         fmod(x, y)
129         
130         Return fmod(x, y), according to platform C.  x % y may differ.
131     
132     frexp(...)
133         frexp(x)
134         
135         Return the mantissa and exponent of x, as pair (m, e).
136         m is a float and e is an int, such that x = m * 2.**e.
137         If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
138     
139     fsum(...)
140         fsum(iterable)
141         
142         Return an accurate floating point sum of values in the iterable.
143         Assumes IEEE-754 floating point arithmetic.
144     
145     gamma(...)
146         gamma(x)
147         
148         Gamma function at x.
149     
150     gcd(...)
151         gcd(x, y) -> int
152         greatest common divisor of x and y
153     
154     hypot(...)
155         hypot(x, y)
156         
157         Return the Euclidean distance, sqrt(x*x + y*y).
158     
159     isclose(...)
160         isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool
161         
162         Determine whether two floating point numbers are close in value.
163         
164            rel_tol
165                maximum difference for being considered "close", relative to the
166                magnitude of the input values
167             abs_tol
168                maximum difference for being considered "close", regardless of the
169                magnitude of the input values
170         
171         Return True if a is close in value to b, and False otherwise.
172         
173         For the values to be considered close, the difference between them
174         must be smaller than at least one of the tolerances.
175         
176         -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
177         is, NaN is not close to anything, even itself.  inf and -inf are
178         only close to themselves.
179     
180     isfinite(...)
181         isfinite(x) -> bool
182         
183         Return True if x is neither an infinity nor a NaN, and False otherwise.
184     
185     isinf(...)
186         isinf(x) -> bool
187         
188         Return True if x is a positive or negative infinity, and False otherwise.
189     
190     isnan(...)
191         isnan(x) -> bool
192         
193         Return True if x is a NaN (not a number), and False otherwise.
194     
195     ldexp(...)
196         ldexp(x, i)
197         
198         Return x * (2**i).
199     
200     lgamma(...)
201         lgamma(x)
202         
203         Natural logarithm of absolute value of Gamma function at x.
204     
205     log(...)
206         log(x[, base])
207         
208         Return the logarithm of x to the given base.
209         If the base not specified, returns the natural logarithm (base e) of x.
210     
211     log10(...)
212         log10(x)
213         
214         Return the base 10 logarithm of x.
215     
216     log1p(...)
217         log1p(x)
218         
219         Return the natural logarithm of 1+x (base e).
220         The result is computed in a way which is accurate for x near zero.
221     
222     log2(...)
223         log2(x)
224         
225         Return the base 2 logarithm of x.
226     
227     modf(...)
228         modf(x)
229         
230         Return the fractional and integer parts of x.  Both results carry the sign
231         of x and are floats.
232     
233     pow(...)
234         pow(x, y)
235         
236         Return x**y (x to the power of y).
237     
238     radians(...)
239         radians(x)
240         
241         Convert angle x from degrees to radians.
242     
243     sin(...)
244         sin(x)
245         
246         Return the sine of x (measured in radians).
247     
248     sinh(...)
249         sinh(x)
250         
251         Return the hyperbolic sine of x.
252     
253     sqrt(...)
254         sqrt(x)
255         
256         Return the square root of x.
257     
258     tan(...)
259         tan(x)
260         
261         Return the tangent of x (measured in radians).
262     
263     tanh(...)
264         tanh(x)
265         
266         Return the hyperbolic tangent of x.
267     
268     trunc(...)
269         trunc(x:Real) -> Integral
270         
271         Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.
272 
273 DATA
274     e = 2.718281828459045
275     inf = inf
276     nan = nan
277     pi = 3.141592653589793
278 
279 FILE
280     (built-in)
281 
282 
283 >>> 
代码块1.3.2.2

  常用内置函数及其功能简要说明如表1.3.2.3所示,其中方括号内的参数可以忽略

 
函数 功能简要说明
abs(x) 返回数字 x 的绝对值或复数的模
all(iterable) 如果对于可迭代对象iterable中所有元素 x 都有 bool(x) 为 True,则返回 True。对于空的可迭代对象也返回 True
any(iterable) 只要可迭代iterable中存在元素x使得bool(x)为True,则返回True。对于空的可迭代对象返回False
bin(x) 将数字x转换为二进制
bool(x) 返回与x等价的布尔值 True 或 False
callable(object) 测试对象object是否可调用,类和函数是可调用的,包含__call__()方法的类的对象也是可调用的
compile() 用于把Python代码编译成可被 exec() 或 eval() 函数执行的代码对象
chr(x) 返回Unicode编码为x的字符 
dir(obj) 返回指定对象obj或模块obj的成员列表 
eval(s[,globals[,locals]])  计算并返回字符串 s 中表达式的值
exec(x)   执行代码或代码对象 x 
filter(func,seq)  返回filter对象,其中包含序列seq中使得单参数函数func返回值为True的那些元素,如果函数func为None则返回那些值等价于True的元素 
float(x)  把数字或字符串x转换为浮点数并返回
hasattr(obj,name)    测试对象obj是否具有成员name 
hash(x) 返回对象 x 的哈希值,如果 x 不可哈希则抛出异常 
help(obj) 返回对象obj的帮助信息 
hex(x) 把数字x转换为十六进制 
id(obj) 返回对象obj的帮助信息 
input([提示内容字符串]) 接收键盘输入的内容,返回字符串 
int(x[,d]) 返回数字x的整数部分,或把d进制的字符串转换为十进制并返回,d默认为十进制 
isinstance(object,class-or-type-or-tuple)  测试对象object是否属于指定类型(如果有多个类型的话需要放到tuple中)的实例
len(obj)  返回对象obj包含的元素个数,适用于列表、元组、集合、字典、字符串、range对象和其他可迭代类型的对象 
list([x])、set([x])、tuple([x])、dict([x]) 把对象x转换为列表、集合、元组、或字典并返回,或生成空列表、空集合、空元组、空字典
map(func,seq) 将函数func映射至序列seq中每个元素,返回包含函数值的map对象 
max(x)、min(x) 返回序列x中的最大值、最小值,要求序列x中的所有元素之间可比较大小 
next(x) 返回可迭代对象x中的下一个元素 
sum(x) 返回序列x中所有元素之和,要求序列x中的所有元素必须为数字 
oct(x) 把数字x转换为八进制 
open(name[,mode]) 以指定模式mode打开文件name并返回文件对象 
ord(x)   返回一个字符x的Unicode编码 
pow(x,y) 返回x的y次方,等价于x **y 

print(value,...,sep=\'\',end=\'\\n\',file=

sys.stdout,flush=False)

基本输出函数 
21个常用代码片段

Python中的常用内置函数都有哪些呢?

常用Javascript代码片段集锦

nodejs常用代码片段

python 8个常用内置函数解说

python自定义函数常用内置函数

(c)2006-2024 SYSTEM All Rights Reserved IT常识