1

I've defined a function that takes as an input a positive integer and returns the sum of its digits:

def digitSum(n):
    exp = 0
    digitSum = 0
    while n%(10**exp) != n:
        digitSum += (n%(10**(exp+1))-n%(10**(exp)))/(10**exp)
        exp += 1
    return digitSum

It seems that if n < 10**9, then digitSum returns an int and returns a long otherwise. If I want it to always return an int, I could have it return int(digitSum) rather than digitSum, so that is not the issue. My question is why does this return a long in the first place?

  • 1
    Why do you care? In Python 3 `long` is gone anyway and replaced by a smarter `int`... And fyi, I'd rewrite your function like this: `sum(map(int, str(n)))` - more readable and probably also faster. – ThiefMaster Aug 11 '14 at 16:03
  • I was unaware of the map function. Thanks! –  Aug 11 '14 at 16:45

2 Answers2

4

Python <3 automatically converts int to an long if the number gets too big. You can read more about it here.

How does Python manage int and long?

(this automatic conversion is one of the reasons python is more memory consuming and slower than lets say C/C++ but that is another discussion)

>>> import sys
>>> x = sys.maxint             # set a variable to your systems maximum integer
>>> print type(x)
<type 'int'>                   # type is then set to int
>>> x += 1                     # if you increase it, it gets converted into long
>>> print type(x)
<type 'long'>
Community
  • 1
  • 1
theAlse
  • 5,577
  • 11
  • 68
  • 110
0

Python 2 differentiates between integers that can be stored in the machine's underlying int type (int) and arbitrary-precision integers that are implemented in the language (long). You can't force your function to return an int (without introducing overflow errors, anyway), since Python 2 automatically creates a long object when the value is too large to fit in an int.

In Python 3, the distinction was removed from the Python level: all values are ints, regardless of magnitude, and any finer distinction is an implementation detail of the builtin int type.

chepner
  • 497,756
  • 71
  • 530
  • 681