Home > Enterprise >  i'm not able to understand this even if i return the value for base condition
i'm not able to understand this even if i return the value for base condition

Time:02-03

i tried to solve sum of digits using recursion but it's throwing nonetype error

def sumofdigits(n):
    if n>=0 and int(n)==n:
        if n==0:
            return 0
        else:
            return (n) sumofdigits((n/10))
print(sumofdigits(113))
TypeError                                 Traceback (most recent call last)
<ipython-input-132-b6ff967381e6> in <module>
      6         else:
      7             return (n) sumofdigits((n/10))
----> 8 print(sumofdigits(113))
      9 

<ipython-input-132-b6ff967381e6> in sumofdigits(n)
      5             return 0
      6         else:
----> 7             return (n) sumofdigits((n/10))
      8 print(sumofdigits(113))
      9 

TypeError: unsupported operand type(s) for  : 'int' and 'NoneType'

this is the error which i got can anyone please explain this

CodePudding user response:

Using n / 10 produces a floating point value, which if you pass to sumofdigits makes int(n) == n false, leading to your recursive call returning None.

Use n // 10 instead to get the correct integer quotient. Now you don't need to check if int(n) == n. Further, unless you pass an negative number, n // 10 will never be negative. You can eliminate the entire conditional that could result in sumofdigits implicitly returning None.

def sumofdigits(n):
    if n==0:
        return 0
    else:
        return (n) sumofdigits((n//10))

You can also use divmod to get the both the quotient and the remainder in one operation, rather than using % and // separately.

def sumofdigits(n):
    if n==0:
        return 0
    else:
        q, r = divmod(n, 10)
        return r   sumofdigits(q)

(If you need to handle a negative argument, I'd add something like

if n < 0:
    return sumofdigits(-n)

to the beginning of the function. )

CodePudding user response:

As @chepner has mentioned the problem is the n/10 instead of n//10. This leads to 113 becoming 11.3 and then the if statement fails and so the function doesn't produce a return value aka None. And None added to your int produces the error.

  •  Tags:  
  • Related