
上QQ阅读APP看书,第一时间看更新
4.2 int类型
整数数据类型(int)是表示整数的数据类型。与其他计算机语言有精度限制不同,Python中的整数位数可以为任意长度(只受限制于计算机内存)。整型对象是不可变对象。
4.2.1 整型字面量
数字字符串(前面可以带负号“-”)即整型字面量。Python解释器自动创建int型对象实例。
数字字符串通常被解释为十进制(基数为10),可以用前缀表示其他进制的整数,但跟在前缀后面的数字必须适合于数制。整型字面量如表4-1所示。
表4-1 整型字面量

【例4.1】 整型字面量示例。

说明:Python 3.7支持使用下画线作为整数或者浮点数的千分位标记,以增强大数值的可阅读性。二进制、八进制、十六进制则使用下画线区分4位标记。
4.2.2 int对象
int是Python内置的数据类型,用户可以创建int类型的对象实例,其基本形式如下。

通过创建int对象可以把数值或任何符合格式的字符串或其他对象转换为int对象。
注意:如果对象x不能转换为整型,则导致TypeError;如果对象x转换失败,则导致ValueError。
【例4.2】 int对象示例。

4.2.3 int对象的方法
int对象i包含的主要方法如下。

【例4.3】 int对象方法示例。

4.2.4 整数的运算
整数对象支持关系运算、算术运算、位运算符、内置函数、math模块中的数学运算函数以及int对象方法(参见4.2.3节)等运算操作。
在Python语言中,常用的int数据类型对象的运算表达式如表4-2所示。
表4-2 常用的int数据类型表达式

【例4.4】 整数运算示例(int_ops.py)。

程序运行结果如图4-1所示。

图4-1 整数运算示例程序运行结果