如何在Python中表示整数的最小值和最大值?在Java中,我们有Integer。MIN_VALUE和Integer.MAX_VALUE。


请参见:Python中的最大浮点数是什么?


当前回答

我非常依赖这样的命令。

python -c 'import sys; print(sys.maxsize)'

返回的最大int值:9223372036854775807

有关'sys'的更多参考,您可以访问

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

其他回答

你可以这样使用'inf':

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

参考:math -数学函数

sys。maxsize常量已从Python 3.0开始移除,取而代之的是使用sys.maxsize。

Integers PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type. ... The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

对于Python 3,它是

import sys
max_size = sys.maxsize
min_size = -sys.maxsize - 1

下面给出的代码将帮助您。 对于最大值,可以使用sys。对于Maxsize和minimum,您可以对相同的值进行否定并使用它。

import sys 

ni=sys.maxsize
print(ni)

在Python中,一旦传入sys值,整数将自动从固定大小的int表示转换为可变宽度的长表示。Maxint,它是231 - 1或263 - 1,这取决于你的平台。注意这里加了个L

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

来自Python手册:

数字是由数字字面值或作为内置函数和操作符的结果创建的。未经修饰的整数字面量(包括二进制、十六进制和八进制数)产生普通整数,除非它们所表示的值太大,不能用普通整数表示,在这种情况下,它们产生长整数。带'L'或'L'后缀的整数字面值会产生长整数('L'是首选,因为1l看起来太像11了!)

Python非常努力地假装它的整数是数学整数并且是无界的。例如,它可以轻松计算googol:

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L