目录
掌握Python两种数据类型的使用方法。
Python 3.12.0
数字类型有三种,分别是:
另外,布尔值类型(bool)是整数类型的子类型。
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.
译文:
有三种不同的数字类型:整数、浮点数和复数。此外,布尔值是整数的一个子类型。
加法(+)
- a=1
- b=2
- #结果:3
- print(a+b)
减法(-)
- a=1
- b=2
- #结果:-1
- print(a-b)
乘法(*)
- a=1
- b=2
- #结果:2
- print(a*b)
除法(/)
- a=1
- b=2
- #结果:0.5
- print(a/b)
整除(//)
- a=-2
- b=-3.14
- c=6
- d=-9
- e=27
-
- #输出:-1
- print(a//c)
- #输出:-3
- print(e//d)
- #输出:3.0
分析:3.14向下取整是3.0,因为b是浮点数,所以最终结果也是浮点数。 - print(b//-1,type(b//-1))
- #输出:-4.0
分析:-3.14向下取整是-4.0,因为b是浮点数,所以最终结果也是浮点数。 - print(b//1,type(b//1))
- #输出:1.0
分析:因为b是浮点数,所以最终结果也是浮点数。 - print(b//b,type(b//b)))
取余、取模(%)
注意:在Python中,商是向下取整的。下面的第二题做了详细的分析。
- a=5
- b=2
- #结果:1
- print(a%b)
-
- a=-5
- b=2
- #结果:1
- #分析:a/b=-2.5,向下取整是-3,余数=被除数-除数*商,即余数=-5-2*(-3)=1
- print(a%b)
-
- a=5
- b=-2
- #结果:-1
- print(a%b)
-
- a=-5
- b=-2
- #结果:-1
- print(a%b)
幂运算(**)
- a=5
- b=2
- #结果:25
- #5的2次方是25
- print(a**b)
规则
案例
- a=5
- b=3.14
- c="3.14"
- d=-1.6
- e="9"
-
- #输出:
- print(type(a),type(b),type(c),type(d))
- #输出:3
原因:3.14向下取整是3 - print(int(b),type(int(b)))
- #输出:-1
原因:-1.6向上取整是-1 - print(int(d),type(int(d)))
- #输出:3
原因:"3.14"不是整数字符串类型,不可以直接转换,需要先转换成float,再转成整数。 - print(int(float(c)),type(int(float(c))))
- #输出:9
分析:"9"是整数字符串类型,可以直接转换 - print(int(e),type(int(e)))
案例
- a=5
- b=3.14
- c="3.14"
- d=-1.6
- e="9"
-
- #输出:
- print(type(a),type(b),type(c),type(d))
- #输出:3.14
- print(float(c),type(float(c)))
- #输出:5.0
- print(float(a),type(float(a)))
案例
- a=-0.618
- #输出:0.618
- print(abs(a))
规则
案例
- a=3.14
- b=-3.876
- c=10086.1314
- #输出:3
分析:四舍五入取整。 - print(round(a),type(round(a)))
- #输出:-4
分析:四舍五入取整。 - print(round(b),type(round(b)))
- #输出:10100.0
分析:第2个参数是负数,则四舍五入到小数点左边的第y位。 - print(round(c,-2),type(round(c,-2)))
案例
- a = 16
- # 十进制转二进制
- print(bin(a))
- # 十进制转十六进制
- print(hex(a))
-
- b = 0b10000
- #二进制转十六进制
- print(hex(b))
- # 二进制转十进制
- b = "0b10000"
- print(int(b,2))
-
- c=0x10
- #十六进制转二进制
- print(bin(c))
- #十六进制转十进制
- c="0x10"
- print(int(c,16))
官方文档
math — Mathematical functions
https://docs.python.org/3/library/math.html案例
- import math
-
- # 计算平方根
- sqrt_result = math.sqrt(16)
- # 输出: 4.0
- print("平方根:", sqrt_result)
-
- # 计算绝对值
- absolute_value = math.fabs(-3.14)
- # 输出: 3.14
- print("绝对值:", absolute_value)
-
- # 计算向上取整
- ceil_result = math.ceil(3.14)
- # 输出: 4
- print("向上取整:", ceil_result)
-
- # 计算向下取整
- floor_result = math.floor(3.14)
- # 输出: 3
- print("向下取整:", floor_result)
-
- # 计算e的x次方
- exp_result = math.exp(2)
- # 输出: 7.38905609893065
- print("e的2次方:", exp_result)
-
- # 计算对数
- log_result = math.log(100, 10)
- # 输出: 2.0
- print("以10为底的100的对数:", log_result)
-
- # 计算π的值
- pi_value = math.pi
- # 输出: 3.141592653589793
- print("π的值:", pi_value)
-
- # 计算正弦值
- # math.sin()接受弧度,需要将角度转换为弧度
- sin_result = math.sin(math.radians(90))
- # 输出: 1.0
- print("正弦值:", sin_result)