I.数字类型
类型 | 说明 | 样例 |
int | 整数 | 1,2,3,100... |
float | 浮点数 | 3.14,2.1,5.6... |
complex | 复数 | complex(1,2) |
bool | 布尔值 | True 和 False |
定义方式:变量名= 值
II.计算与类型转换
1)计算
1,计算支持比较,算术,逻辑运算符。
2,不同数字类型间的计算:
- 整数与整数间计算,结果取决于运算符
- 整数与浮点数间的计算,结果是浮点数
- 整数与复数间的计算,结果是复数,例如:
a=4/2
a2=4+2
#Output:2.0 6
#不同的运算符,结果是不同的数据类型
b=4.0//2
c=4.0+2
#Output:2.0 6.0
#浮点数和整数运算得到浮点数
d=5+complex(3,2)
#Output:(8+2j)
#整数和复数运算得到复数
2)类型转换规则
默认转换顺序: complex>float>int>bool
类型强制转换:
1,转换方式
方法 | 说明 | 示例 |
int(x) | 将x转换为int类型 | int(3.14) ->3 |
int(x,base=10) | 将数字字符串转换为整数,base为进制,默认为10进制 | int(a,‘10’) ->2 |
float(x) | 将数字或字符串转为浮点数 | float('3') ->3.0 |
bool(x) | 将任意对象转换为bool类型 | bool(1)->True bool(0)->False |
2,示例:
#转为整数
pi=3.14
print(int(pi))#Output:3
#转为浮点数
a=4
print(float(a))#Output:4.0
#不同进制的整数转换
b='16'
print(int(b,8))#Output:14
c= 10
#print(int(c,2))#TypeError:int() can't convert non-string with explicit base
#bool类型
print(bool(3.14))
print(bool('kind'))
print(bool(0.0))
#Output:
#True
#True
#False
如示例c=10,整数的进制是不可更改的。
III.数字相关函数
1,基本函数
函数 | 说明 |
round(number, ndigits=None) | 指定小数后位数 |
pow(x,y,z=None,/) | x**y 或x**y%z |
abs(x,/) | x的绝对值 |
例如:
print(round(3.1415,2))
print(pow(4,2,2))
print(abs(-10))
'''
Output:
3.14
0
10
'''
2,math 模块
使用方式:import math
数字常数:
常数 | 说明 |
pi | 圆周率 |
e | 自然对数的底数 |
三角函数:
函数 | 说明 |
sin(x)/cos(x) | 返回正弦和余弦值 |
asin(x)/acos(x) | 返回反正弦和反余弦弧度值 |
tan(x) | 返回正切值 |
atan(x) | 返回反正切弧度值 |
指数函数:
函数 | 说明 |
factorial(x) | 计算阶乘x! |
sqrt(x) | 计算x的平方根 |
floor(x) | 取最接近x的整数,返回值小于x |
log(x[, base]) | 以base为底的x的对数 |
log10(x) | 以10为底的对数 |
log2(x) | 以2为底的对数 |
示例:
import math
a=4
b=math.sin(a)
c=math.floor(4.5)
print(b,c)
#Output: -0.7568024953079282 4
3,random模块
常用函数:
方法 | 说明 |
random() | 产生[0,1]之间随机浮点数 |
uniform(a,b) | 产生(min(a,b),max(a,b))之间随机浮点数 |
randint(a,b) | 产生[a,b]之间随机整数 |
seed(a=None, version=2) | 产生设置随机数的种子,用于确保多次产生的随机数相同 |
randrange([start,] stop [,step]) | 指定范围内,按step递增的集合中取一个随机数,step缺省值为1) |
使用示例:
import random
print(random.random())
#随机打印一个浮点数
print(random.uniform(10,1))
#随机打印[1,10]之间的一个浮点数
print(random.randint(1,10))
#随机打印[1,10]之间的一个整数
print(random.randrange(0,11,2))
#随机打印[0,2,4,6,8,10]中任意一个数
#seed()设置随机数种子为0
random.seed(0)
b=random.randint(0,10)
print(b)
#Output:6
random.seed(0)
c=random.randint(0,10)
print(c)
#Output:6
IV.总结
1,数字有关的数据类型
2,数字类型转换
3,数字相关函数和模块,包括round(),pow(),abs();math模块,random模块等