A Harshad number is an integer that is divisible by the sum of its digits (for example, 21 is divisible by $2+1=3$ and so is a Harshad number). Correct the following code which should return True
or False
if n
is a Harshad number or not respectively:
def digit_sum(n):
""" Find the sum of the digits of integer n. """
s_digits = list(str(n))
dsum = 0
for s_digit in s_digits:
dsum += int(s_digit)
def is_harshad(n):
return not n % digit_sum(n)
When run, the function is_harshad
raises an error:
>>> is_harshad(21)
TypeError: unsupported operand type(s) for %: 'int' and 'NoneType'
The problem is that the function digit_sum
does not return the sum of the digits of n
that it has calculated. In the absence of an explicit return
statement, a Python function returns None
, but None
isn't an acceptable object to use in a modulus calculation and so a TypeError
is raised.
The fix is simply to add return dsum
:
def digit_sum(n):
""" Find and return the sum of the digits of integer n. """
s_digits = list(str(n))
dsum = 0
for s_digit in s_digits:
dsum += int(s_digit)
return dsum
def is_harshad(n):
return not n % digit_sum(n)
Now, as expected:
>>> is_harshad(21)
True