Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

python - Difference between int() and long()

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, "", type(number)

number = long(number_string) # cast it to long
print number, "", type(number)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 3.x and above, you can use int() instead of long().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...