Python 3 数字(Number)详解
                           
天天向上
发布: 2025-03-14 22:16:03

原创
321 人浏览过

Python 3 提供了多种数值类型,主要包括 整数(int)、浮点数(float)、复数(complex)。此外,Python 还支持 进制转换、数学运算、随机数和数学函数


1. 数字类型

Python 3 主要支持三种数值类型:

类型说明示例
int整数,没有大小限制10, -5, 1000000
float浮点数,带小数点或科学计数法3.14, -0.001, 1.2e3
complex复数,包含实部和虚部2 + 3j, -1.5 + 2.7j

📌 示例代码:

a = 10        # 整数
b = 3.14      # 浮点数
c = 2 + 3j    # 复数
print(type(a))  # <class 'int'>
print(type(b))  # <class 'float'>
print(type(c))  # <class 'complex'>

2. 数值运算

Python 允许对数值进行加、减、乘、除等运算:

运算符说明示例结果
+加法5 + 38
-减法10 - 46
*乘法6 * 212
/除法(返回浮点数)9 / 24.5
//整除(向下取整)9 // 24
%取余(取模)9 % 21
**幂运算2 ** 38

📌 示例代码:

a, b = 9, 2
print(a + b)  # 11
print(a - b)  # 7
print(a * b)  # 18
print(a / b)  # 4.5
print(a // b) # 4
print(a % b)  # 1
print(a ** b) # 81

3. 进制表示

Python 支持二进制、八进制、十六进制的整数表示:

进制语法示例结果(十进制)
二进制0b 开头0b101010
八进制0o 开头0o1210
十六进制0x 开头0xA10

📌 示例代码:

print(0b1010)  # 10
print(0o12)    # 10
print(0xA)     # 10

4. 类型转换

Python 提供了 int()float()complex() 进行数值类型转换。

方法说明示例结果
int(x)转换为整数int(3.6)3
float(x)转换为浮点数float(5)5.0
complex(x, y)转换为复数complex(2, -3)(2-3j)

📌 示例代码:

print(int(3.9))       # 3
print(float(10))      # 10.0
print(complex(2, 5))  # (2+5j)

5. 常用数学函数

Python 内置 math 模块 提供了数学计算函数

📌 引入 math 模块

import math
方法说明示例结果
math.ceil(x)向上取整math.ceil(3.4)4
math.floor(x)向下取整math.floor(3.9)3
math.sqrt(x)平方根math.sqrt(9)3.0
math.pow(x, y)xy 次幂math.pow(2, 3)8.0
math.fabs(x)绝对值math.fabs(-10)10.0
math.factorial(x)阶乘math.factorial(5)120
math.log(x, base)对数math.log(8, 2)3.0
math.sin(x)正弦math.sin(math.pi/2)1.0
math.cos(x)余弦math.cos(0)1.0
math.tan(x)正切math.tan(math.pi/4)1.0

📌 示例代码:

import math
print(math.ceil(3.4))   # 4
print(math.floor(3.9))  # 3
print(math.sqrt(16))    # 4.0
print(math.pow(2, 3))   # 8.0
print(math.factorial(5))# 120

6. 生成随机数

Python 提供了 random 模块 用于生成随机数

📌 引入 random 模块

import random
方法说明示例结果
random.randint(a, b)生成 ab 之间的随机整数random.randint(1, 10)3
random.uniform(a, b)生成 ab 之间的随机浮点数random.uniform(1, 5)3.14
random.random()生成 0~1 之间的随机浮点数random.random()0.674
random.choice(seq)从序列 seq 中随机选择一个元素random.choice([1, 2, 3])2
random.shuffle(seq)随机打乱 seqrandom.shuffle(lst)[3, 1, 2]

📌 示例代码:

import random

print(random.randint(1, 10))  # 生成 1 到 10 之间的随机整数
print(random.uniform(1, 5))   # 生成 1 到 5 之间的随机浮点数
print(random.random())        # 生成 0 到 1 之间的随机数
print(random.choice(['a', 'b', 'c']))  # 随机选择 'a', 'b', 'c' 之一

lst = [1, 2, 3, 4, 5]
random.shuffle(lst)
print(lst)  # 打乱列表

总结

  • Python 支持 intfloatcomplex 三种数值类型
  • Python 提供 进制转换、数学运算和数学函数
  • math 模块 提供高级数学函数,random 模块 用于生成随机数。

你可以在 Python 交互模式中尝试这些代码,体验 Python 的强大数值计算功能! 更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *