数字类型函数

python中有一些针对数字类型的函数,有些用于数字类型的转换,另一些则执行一些常用的运算。

序号 函数 功能                           
1 int()  
2 bool()  
3 float()  
4 long()  
5 complax()  
6 abs()  
7 pow()  
8 hex()  
9 oct()  
10 chr()  
11 ord()  
12 round()  
13 math.floor()  
14 math.ceil()  
15 math.sqrt()  
16 divmod()  

1.bool():返回对象的布尔值

>>> bool(1)
True
>>> bool(0)    #除了0之外,其它的数字和字符串都返回True
False
>>> bool('rew')
True
>>> bool(2 >3)
False

2.int():返回一个字符串或数值对象的整数表示。

>>> int('23')
23

  >>> int(1.23)  #有取整的功能
  1

3.long():返回一个字符或数值对象的长整型表示。python3中取消了long。

4.float():返回一个数字或者字符串的浮点型表示。

>>> float(123)
123.0

5.complex():返回一个字符串的复数表示。

>>> complex(12.3)
(12.3+0j)

6.abs():返回给定参数的绝对值。

>>> abs(-1)
1
>>> abs(10.)
10.0
>>> abs(1.2 -2.2j)
2.505992817228334

7.pow():类似于**进行指数运算。

>>> pow(2,3)
8
>>> pow(4,3)
64
>>> pow(4,-2)
0.0625
#pow还可以添加第三个参数,取余
>>> pow(2,3,2)
0
>>> pow(2,3,3)
2

8.divmod():内建函数把除法和取余运算结合起来,返回一个包含商和余数的元祖。

>>> divmod(10,3)
(3, 1)
>>> divmod(10,2)
(5, 0)

9.round(fit,ndig=1):接受一个浮点型fit,并对其进行四舍五入。保留ndig位小数,若不提供ndig参数,则默认小数点后为0位。

>>> round(12.3)
12
>>> round(12.6)
13
>>> round(12.6,1)
12.6
>>> round(12.63,1)
12.6
>>> round(12.66,1)    #对小数点后一位进行四舍五入。
12.7

10.math.floor():向下取值,返回浮点型。

>>> import math
>>> math.floor(12.3)
12
>>> math.floor(12.6)
12

11.math.cell():向上取值,返回浮点型。

>>> math.ceil(12.3)
13
>>> math.ceil(12.6)
13

12.math.sqrt():返回平方根,不适用于负数。负数可用cmath.sqrt()

>>> math.sqrt(9)
3.0
>>> math.sqrt(-9)   #不适用于负数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error
>>> math.sqrt(8)
2.8284271247461903

>>> import cmath
>>> cmath.sqrt(-9)
3j

13.hex():将数字转换成十六进制数并以字符串的形式返回。

>>> hex(12)
'0xc'
>>> hex(233)
'0xe9'

14.oct():将数字转换成八进制数并以字符串的形式返回。

>>> oct(12)
'0o14'
>>> oct(233)
'0o351'

15.chr():将ASCII数字转换成ASCII字符串,范围只能在0到255之间。

>>> chr(65)
'A'
>>> chr(126)
'~'
>>> chr(98)
'b'

16.ord():接受一个ASCII,返回相应的ASCII值

>>> ord(',')
44
>>> ord('a')
97
>>> ord('as')
Traceback (most recent call last):   #
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
原文地址:https://www.cnblogs.com/yangmingxianshen/p/7705563.html