手册目录

Python 教程

浏览2974
更新时间2025-08-06

Python 数字

Python 中有三种数字类型:

  • int
  • float
  • complex

为变量赋值时,将创建数值类型的变量:

实例

x = 10   # int
y = 6.3  # float
z = 2j   # complex

如需验证 Python 中任何对象的类型,请使用 type() 函数:

实例

print(type(x))
print(type(y))
print(type(z))

运行实例

Int

Int 或整数是完整的数字,正数或负数,没有小数,长度不限。

实例

整数:

x = 10
y = 37216654545182186317
z = -465167846

print(type(x))
print(type(y))
print(type(z))

运行实例

Float

浮动或“浮点数”是包含小数的正数或负数。

实例

浮点:

x = 3.50
y = 2.0
z = -63.78

print(type(x))
print(type(y))
print(type(z))

运行实例

浮点数也可以是带有“e”的科学数字,表示 10 的幂。

实例

浮点:

x = 27e4
y = 15E2
z = -49.8e100

print(type(x))
print(type(y))
print(type(z))

运行实例

复数

复数用 "j" 作为虚部编写:

实例

复数:

x = 2+3j
y = 7j
z = -7j

print(type(x))
print(type(y))
print(type(z))

运行实例

类型转换

您可以使用 int()float()complex() 方法从一种类型转换为另一种类型:

实例

从一种类型转换为另一种类型:

x = 10 # int
y = 6.3 # float
z = 1j # complex

# 把整数转换为浮点数

a = float(x)

# 把浮点数转换为整数

b = int(y)

# 把整数转换为复数:

c = complex(x)

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

运行实例

注释:您无法将复数转换为其他数字类型。

随机数

Python 没有 random() 函数来创建随机数,但 Python 有一个名为 random 的内置模块,可用于生成随机数:

实例

导入 random 模块,并显示 1 到 9 之间的随机数:

import random

print(random.randrange(1,10))

运行实例

在 Random 模块参考手册 中,您将了解有关 Random 模块的更多信息。

相关视频

更多

免费

php8,我来也
初级php8,我来也

321787次学习

收藏

免费

Thinkphp6.0正式版视频教程
中级Thinkphp6.0正式版视频教程

382430次学习

收藏

免费

细说PHP第一季
中级细说PHP第一季

282789次学习

收藏

免费

简单聊聊PHP创业那点事
初级简单聊聊PHP创业那点事

13415次学习

收藏
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号