Python数字类型及类型转换规则
Python Number
Introduction 介绍
Number 数字
There are three different kinds of built-in numbers in Python :
ints
,floats
, andcomplex
. However
有三种内置数字类型:
- ints
- floats
- complex
Arithmetic 计算
# The int is widened to a float here, and a float type is returned. >>> 3 + 4.0 7.0 >>> 3 * 4.0 12.0 >>> 3 - 2.0 1.0 # Division always returns a float. >>> 6 / 2 3.0 >>> 7 / 4 1.75 # Calculating remainders. >>> 7 % 4 3 >>> 2 % 4 2 >>> 12.75 % 3 0.75
特点:
- 类型会自动从窄类型转换为宽类型
- 相除一定会返回float类型
显式类型转换
>>> int(6 / 2) 3 >>> float(1 + 2) 3.0