1、Python支持以下三种数值类型
- 整数:Python3对整数大小没有限制,可以当做long类型用,Python3中没有long类型
- 浮点数
- 复数:Python支持复数,用a+bj或者complex(a,b)来表示,实部a和虚部b都是浮点型
2、数字类型转换
int(x) 将x转换为一个整数
float(x) 将x转换为一个浮点数
complex(x) 将x转换为一个复数,虚部为0
complex(x,y) 将x转换为复数x+yj
**注意:python中数的运算需要注意以下两点:
1、整数与整数间的除法/结果为浮点数,如果需要整除,应使用//
2、混合运算时Python会将整数转换为浮点数**
备注:在交互模式中最后被输出的表达式结果会被赋值给_,参照如下代码:
>>> tax=11.1
>>> price=100
>>> price+price*tax
1210.0
>>> _
1210.0
>>> print(_)
1210.0
>>> round(_)
1210
>>>
3、数学函数
函数 | 描述 |
---|---|
abs(x) | 返回x的绝对值 |
ceil(x) | 返回数字的上入整数 例:ceil(4.1) 返回5 |
exp(x) | 返回e的x次幂 |
fabs(x) | 返回x的绝对值 |
floor(x) | 返回x的下舍整数 例:floor(4.9) 返回4 |
log(x) | 返回x的自然对数 例:math.log(math.e) 返回1.0 |
log10(x) | 返回x以10为基数的对数 |
max(x1,x2,…) | 返回给定参数的最大值,参数部分可为序列 |
min(x1,x2,…) | 返回给定参数的最小值,参数部分可为序列 |
modf(x) | 以元组的形式返回x的整数部分和小数部分,整数部分以浮点数表示 |
pow(x,y) | 返回x**y的值 |
round(x[,n]) | 返回四舍五入值,给出n代表近似到小数点后的位数 |
sqrt(x) | 返回x的平方根 |
>>> abs(-10)
10
>>> math.ceil(4.1)
5
>>> math.exp(1)
2.718281828459045
>>> math.fabs(-10)
10.0
>>> math.floor(5.1)
5
>>> math.log(math.e)
1.0
>>> math.log10(100)
2.0
>>> max(1,2,3,4,5)
5
>>> min((9,8,7,6,5))
5
>>> math.modf(1.23)
(0.22999999999999998, 1.0)
>>> pow(3,2)
9
>>> round(5.1)
5
>>> round(1.25,1)
1.2
>>> math.sqrt(4)
2.0
>>>
4、随机函数
函数 | 描述 |
---|---|
choice(seq) | 从序列的元素中随机挑选一个 |
randrange([start,]stop[,step]) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省时为1 |
random() | 随机生成一个实数,范围[0,1) |
seed([x]) | 改变随机数生成器的种子 |
shuffle(lst) | 将序列中的元素随机排序 |
uniform(x,y) | 随机生成一个实数,范围为[x,y] |
>>> import random
>>> random.choice('hello world')
'l'
>>> random.choice([1,2,3,4,5,6])
5
>>> random.randrange(100)
94
>>> random.randrange(30,100,5)
65
>>> random.random()
0.009375685786666255
>>> random.seed()
>>> random.seed(3)
>>> a=(1,2,3,4,5,6)
>>> random.shuffle(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\python\Python36\lib\random.py", line 275, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item assignment
>>> a=[1,2,3,4,5,6]
>>> random.shuffle(a)
>>> a
[1, 3, 4, 2, 6, 5]
>>> random.uniform(1.1,1.2)
1.1625720304108054
5、数学常量
常量 | 描述 |
---|---|
pi | 圆周率 |
e | 自然常数 |
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>>