user3930206
user3930206

Reputation:

Why does this function return a long rather than an int?

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?

Upvotes: 1

Views: 1753

Answers (2)

theAlse
theAlse

Reputation: 5747

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'>

Upvotes: 4

chepner
chepner

Reputation: 531858

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.

Upvotes: 0

Related Questions