Python数字类型及类型转换规则

CalvinZhao-Blog / 2023-08-15 / 原文

Python Number

Introduction 介绍

Number 数字

There are three different kinds of built-in numbers in Python : ints, floats, and complex. However

有三种内置数字类型:

  1. ints
  2. floats
  3. 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

特点

  1. 类型会自动从窄类型转换为宽类型
  2. 相除一定会返回float类型

显式类型转换

>>> int(6 / 2)
3
>>> float(1 + 2)
3.0