Difference between int() and long()

被刻印的时光 ゝ 提交于 2020-01-03 13:43:30

问题


What is the difference between int(x) and long(x) in python

My understanding:

  1. long() will always return a long
  2. int() will return an int or a long (if its too big)
  3. so int() is sufficient to dynamically get a int/long based on its value

So unless above (1) (2) (3) are incorrect, why do you need long()? when int() gets the job done? skipping long() for all number ranges will hurt me?


Documentation refered:

class int(x=0)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, it can be a plain integer, a long integer, or a floating point number. If x is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.

class long(x=0)

Return a long integer object constructed from a string or number x. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The base argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.


code experimented

number = int(number_string) # cast it to integer
print number, "\t", type(number)

number = long(number_string) # cast it to long
print number, "\t", type(number)

回答1:


int: Integers; equivalent to C longs in Python 2.x, non-limited length in Python 3.x

long: Long integers of non-limited length; exists only in Python 2.x

So, in python 3x and aboue you can use int() and no need to use long().

Hope this clears your doubt?



来源:https://stackoverflow.com/questions/47248385/difference-between-int-and-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!